`.
- style: The style of the component.
- key: A unique key for the component.
- id: The id for the component.
- class_name: The class name for the component.
- autofocus: Whether the component should take the focus once the page is loaded
- custom_attrs: custom attribute
- **props: The props of the component.
-
- Returns:
- The component.
- """
- ...
diff --git a/reflex/components/chakra/typography/text.py b/reflex/components/chakra/typography/text.py
deleted file mode 100644
index e211c4d64..000000000
--- a/reflex/components/chakra/typography/text.py
+++ /dev/null
@@ -1,17 +0,0 @@
-"""A text component."""
-from __future__ import annotations
-
-from reflex.components.chakra import ChakraComponent
-from reflex.vars import Var
-
-
-class Text(ChakraComponent):
- """Render a paragraph of text."""
-
- tag = "Text"
-
- # Override the tag. The default tag is ``.
- as_: Var[str]
-
- # Truncate text after a specific number of lines. It will render an ellipsis when the text exceeds the width of the viewport or max_width prop.
- no_of_lines: Var[int]
diff --git a/reflex/components/chakra/typography/text.pyi b/reflex/components/chakra/typography/text.pyi
deleted file mode 100644
index 889039784..000000000
--- a/reflex/components/chakra/typography/text.pyi
+++ /dev/null
@@ -1,91 +0,0 @@
-"""Stub file for reflex/components/chakra/typography/text.py"""
-# ------------------- DO NOT EDIT ----------------------
-# This file was generated by `reflex/utils/pyi_generator.py`!
-# ------------------------------------------------------
-
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from reflex.components.chakra import ChakraComponent
-from reflex.vars import Var
-
-class Text(ChakraComponent):
- @overload
- @classmethod
- def create( # type: ignore
- cls,
- *children,
- as_: Optional[Union[Var[str], str]] = None,
- no_of_lines: Optional[Union[Var[int], int]] = None,
- style: Optional[Style] = None,
- key: Optional[Any] = None,
- id: Optional[Any] = None,
- class_name: Optional[Any] = None,
- autofocus: Optional[bool] = None,
- custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
- ) -> "Text":
- """Create the component.
-
- Args:
- *children: The children of the component.
- as_: Override the tag. The default tag is `
`.
- no_of_lines: Truncate text after a specific number of lines. It will render an ellipsis when the text exceeds the width of the viewport or max_width prop.
- style: The style of the component.
- key: A unique key for the component.
- id: The id for the component.
- class_name: The class name for the component.
- autofocus: Whether the component should take the focus once the page is loaded
- custom_attrs: custom attribute
- **props: The props of the component.
-
- Returns:
- The component.
- """
- ...
diff --git a/reflex/components/component.py b/reflex/components/component.py
index 39a97792e..85db3906d 100644
--- a/reflex/components/component.py
+++ b/reflex/components/component.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import copy
+import dataclasses
import typing
from abc import ABC, abstractmethod
from functools import lru_cache, wraps
@@ -24,6 +25,8 @@ from typing import (
import reflex.state
from reflex.base import Base
from reflex.compiler.templates import STATEFUL_COMPONENT
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.components.dynamic import load_dynamic_serializer
from reflex.components.tags import Tag
from reflex.constants import (
Dirs,
@@ -34,19 +37,39 @@ from reflex.constants import (
MemoizationMode,
PageNames,
)
+from reflex.constants.compiler import SpecialAttributes
from reflex.event import (
+ EventCallback,
EventChain,
+ EventChainVar,
EventHandler,
EventSpec,
+ EventVar,
call_event_fn,
call_event_handler,
+ empty_event,
get_handler_args,
)
from reflex.style import Style, format_as_emotion
-from reflex.utils import console, format, imports, types
-from reflex.utils.imports import ImportVar
-from reflex.utils.serializers import serializer
-from reflex.vars import BaseVar, Var, VarData
+from reflex.utils import format, imports, types
+from reflex.utils.imports import (
+ ImmutableParsedImportDict,
+ ImportDict,
+ ImportVar,
+ ParsedImportDict,
+ parse_imports,
+)
+from reflex.vars import VarData
+from reflex.vars.base import (
+ CachedVarOperation,
+ LiteralVar,
+ Var,
+ cached_property_no_lock,
+)
+from reflex.vars.function import ArgsFunctionOperation, FunctionStringVar
+from reflex.vars.number import ternary_operation
+from reflex.vars.object import ObjectVar
+from reflex.vars.sequence import LiteralArrayVar
class BaseComponent(Base, ABC):
@@ -95,7 +118,7 @@ class BaseComponent(Base, ABC):
"""
@abstractmethod
- def _get_all_imports(self) -> imports.ImportDict:
+ def _get_all_imports(self) -> ParsedImportDict:
"""Get all the libraries and fields that are used by the component.
Returns:
@@ -187,7 +210,7 @@ class Component(BaseComponent, ABC):
class_name: Any = None
# Special component props.
- special_props: Set[Var] = set()
+ special_props: List[Var] = []
# Whether the component should take the focus once the page is loaded
autofocus: bool = False
@@ -213,7 +236,7 @@ class Component(BaseComponent, ABC):
# State class associated with this component instance
State: Optional[Type[reflex.state.State]] = None
- def add_imports(self) -> dict[str, str | ImportVar | list[str | ImportVar]]:
+ def add_imports(self) -> ImportDict | list[ImportDict]:
"""Add imports for the component.
This method should be implemented by subclasses to add new imports for the component.
@@ -241,7 +264,7 @@ class Component(BaseComponent, ABC):
"""
return {}
- def add_hooks(self) -> list[str]:
+ def add_hooks(self) -> list[str | Var]:
"""Add hooks inside the component function.
Hooks are pieces of literal Javascript code that is inserted inside the
@@ -319,7 +342,8 @@ class Component(BaseComponent, ABC):
# Set default values for any props.
if types._issubclass(field.type_, Var):
field.required = False
- field.default = Var.create(field.default)
+ if field.default is not None:
+ field.default = LiteralVar.create(field.default)
elif types._issubclass(field.type_, EventHandler):
field.required = False
@@ -348,7 +372,7 @@ class Component(BaseComponent, ABC):
"id": kwargs.get("id"),
"children": children,
**{
- prop: Var.create(kwargs[prop])
+ prop: LiteralVar.create(kwargs[prop])
for prop in self.get_initial_props()
if prop in kwargs
},
@@ -360,7 +384,6 @@ class Component(BaseComponent, ABC):
# Get the component fields, triggers, and props.
fields = self.get_fields()
component_specific_triggers = self.get_event_triggers()
- triggers = component_specific_triggers.keys()
props = self.get_props()
# Add any events triggers.
@@ -370,13 +393,17 @@ class Component(BaseComponent, ABC):
# Iterate through the kwargs and set the props.
for key, value in kwargs.items():
- if key.startswith("on_") and key not in triggers and key not in props:
+ if (
+ key.startswith("on_")
+ and key not in component_specific_triggers
+ and key not in props
+ ):
raise ValueError(
f"The {(comp_name := type(self).__name__)} does not take in an `{key}` event trigger. If {comp_name}"
f" is a third party component make sure to add `{key}` to the component's event triggers. "
- f"visit https://reflex.dev/docs/wrapping-react/logic/#event-triggers for more info."
+ f"visit https://reflex.dev/docs/wrapping-react/guide/#event-triggers for more info."
)
- if key in triggers:
+ if key in component_specific_triggers:
# Event triggers are bound to event chains.
field_type = EventChain
elif key in props:
@@ -392,7 +419,10 @@ class Component(BaseComponent, ABC):
passed_types = None
try:
# Try to create a var from the value.
- kwargs[key] = Var.create(value)
+ if isinstance(value, Var):
+ kwargs[key] = value
+ else:
+ kwargs[key] = LiteralVar.create(value)
# Check that the var type is not None.
if kwargs[key] is None:
@@ -417,7 +447,9 @@ class Component(BaseComponent, ABC):
if types.is_union(passed_type):
# We need to check all possible types in the union.
passed_types = (
- arg for arg in passed_type.__args__ if arg is not type(None)
+ arg
+ for arg in passed_type.__args__ # type: ignore
+ if arg is not type(None)
)
if (
# If the passed var is a union, check if all possible types are valid.
@@ -428,30 +460,56 @@ class Component(BaseComponent, ABC):
) or (
# Else just check if the passed var type is valid.
not passed_types
- and not types._issubclass(passed_type, expected_type)
+ and not types._issubclass(passed_type, expected_type, value)
):
- value_name = value._var_name if isinstance(value, Var) else value
- raise TypeError(
- f"Invalid var passed for prop {type(self).__name__}.{key}, expected type {expected_type}, got value {value_name} of type {passed_types or passed_type}."
+ value_name = value._js_expr if isinstance(value, Var) else value
+
+ additional_info = (
+ " You can call `.bool()` on the value to convert it to a boolean."
+ if expected_type is bool and isinstance(value, Var)
+ else ""
)
+ raise TypeError(
+ f"Invalid var passed for prop {type(self).__name__}.{key}, expected type {expected_type}, got value {value_name} of type {passed_type}."
+ + additional_info
+ )
# Check if the key is an event trigger.
- if key in triggers:
+ if key in component_specific_triggers:
# Temporarily disable full control for event triggers.
kwargs["event_triggers"][key] = self._create_event_chain(
- value=value, args_spec=component_specific_triggers[key]
+ value=value, # type: ignore
+ args_spec=component_specific_triggers[key],
+ key=key,
)
# Remove any keys that were added as events.
for key in kwargs["event_triggers"]:
del kwargs[key]
+ # Place data_ and aria_ attributes into custom_attrs
+ special_attributes = tuple(
+ key
+ for key in kwargs
+ if key not in fields and SpecialAttributes.is_special(key)
+ )
+ if special_attributes:
+ custom_attrs = kwargs.setdefault("custom_attrs", {})
+ for key in special_attributes:
+ custom_attrs[format.to_kebab_case(key)] = kwargs.pop(key)
+
# Add style props to the component.
style = kwargs.get("style", {})
if isinstance(style, List):
# Merge styles, the later ones overriding keys in the earlier ones.
style = {k: v for style_dict in style for k, v in style_dict.items()}
+ if isinstance(style, (Breakpoints, Var)):
+ style = {
+ # Assign the Breakpoints to the self-referential selector to avoid squashing down to a regular dict.
+ "&": style,
+ }
+
kwargs["style"] = Style(
{
**self.get_fields()["style"].default,
@@ -459,13 +517,16 @@ class Component(BaseComponent, ABC):
**{attr: value for attr, value in kwargs.items() if attr not in fields},
}
)
- if "custom_attrs" not in kwargs:
- kwargs["custom_attrs"] = {}
# Convert class_name to str if it's list
class_name = kwargs.get("class_name", "")
if isinstance(class_name, (List, tuple)):
- kwargs["class_name"] = " ".join(class_name)
+ if any(isinstance(c, Var) for c in class_name):
+ kwargs["class_name"] = LiteralArrayVar.create(
+ class_name, _var_type=List[str]
+ ).join(" ")
+ else:
+ kwargs["class_name"] = " ".join(class_name)
# Construct the component.
super().__init__(*args, **kwargs)
@@ -474,14 +535,20 @@ class Component(BaseComponent, ABC):
self,
args_spec: Any,
value: Union[
- Var, EventHandler, EventSpec, List[Union[EventHandler, EventSpec]], Callable
+ Var,
+ EventHandler,
+ EventSpec,
+ List[Union[EventHandler, EventSpec, EventVar]],
+ Callable,
],
+ key: Optional[str] = None,
) -> Union[EventChain, Var]:
"""Create an event chain from a variety of input types.
Args:
args_spec: The args_spec of the event trigger being bound.
value: The value to create the event chain from.
+ key: The key of the event trigger being bound.
Returns:
The event chain.
@@ -491,9 +558,16 @@ class Component(BaseComponent, ABC):
"""
# If it's an event chain var, return it.
if isinstance(value, Var):
- if value._var_type is not EventChain:
- raise ValueError(f"Invalid event chain: {value}")
- return value
+ if isinstance(value, EventChainVar):
+ return value
+ elif isinstance(value, EventVar):
+ value = [value]
+ elif issubclass(value._var_type, (EventChain, EventSpec)):
+ return self._create_event_chain(args_spec, value.guess_type(), key=key)
+ else:
+ raise ValueError(
+ f"Invalid event chain: {str(value)} of type {value._var_type}"
+ )
elif isinstance(value, EventChain):
# Trust that the caller knows what they're doing passing an EventChain directly
return value
@@ -504,53 +578,55 @@ class Component(BaseComponent, ABC):
# If the input is a list of event handlers, create an event chain.
if isinstance(value, List):
- events: list[EventSpec] = []
+ events: List[Union[EventSpec, EventVar]] = []
for v in value:
if isinstance(v, (EventHandler, EventSpec)):
# Call the event handler to get the event.
- try:
- event = call_event_handler(v, args_spec)
- except ValueError as err:
- raise ValueError(
- f" {err} defined in the `{type(self).__name__}` component"
- ) from err
-
- # Add the event to the chain.
- events.append(event)
+ events.append(call_event_handler(v, args_spec, key=key))
elif isinstance(v, Callable):
# Call the lambda to get the event chain.
- events.extend(call_event_fn(v, args_spec))
+ result = call_event_fn(v, args_spec, key=key)
+ if isinstance(result, Var):
+ raise ValueError(
+ f"Invalid event chain: {v}. Cannot use a Var-returning "
+ "lambda inside an EventChain list."
+ )
+ events.extend(result)
+ elif isinstance(v, EventVar):
+ events.append(v)
else:
raise ValueError(f"Invalid event: {v}")
# If the input is a callable, create an event chain.
elif isinstance(value, Callable):
- events = call_event_fn(value, args_spec)
+ result = call_event_fn(value, args_spec)
+ if isinstance(result, Var):
+ # Recursively call this function if the lambda returned an EventChain Var.
+ return self._create_event_chain(args_spec, result, key=key)
+ events = [*result]
# Otherwise, raise an error.
else:
raise ValueError(f"Invalid event chain: {value}")
# Add args to the event specs if necessary.
- events = [e.with_args(get_handler_args(e)) for e in events]
-
- # Collect event_actions from each spec
- event_actions = {}
- for e in events:
- event_actions.update(e.event_actions)
+ events = [
+ (e.with_args(get_handler_args(e)) if isinstance(e, EventSpec) else e)
+ for e in events
+ ]
# Return the event chain.
if isinstance(args_spec, Var):
return EventChain(
events=events,
args_spec=None,
- event_actions=event_actions,
+ event_actions={},
)
else:
return EventChain(
events=events,
args_spec=args_spec,
- event_actions=event_actions,
+ event_actions={},
)
def get_event_triggers(self) -> Dict[str, Any]:
@@ -558,33 +634,35 @@ class Component(BaseComponent, ABC):
Returns:
The event triggers.
+
"""
default_triggers = {
- EventTriggers.ON_FOCUS: lambda: [],
- EventTriggers.ON_BLUR: lambda: [],
- EventTriggers.ON_CLICK: lambda: [],
- EventTriggers.ON_CONTEXT_MENU: lambda: [],
- EventTriggers.ON_DOUBLE_CLICK: lambda: [],
- EventTriggers.ON_MOUSE_DOWN: lambda: [],
- EventTriggers.ON_MOUSE_ENTER: lambda: [],
- EventTriggers.ON_MOUSE_LEAVE: lambda: [],
- EventTriggers.ON_MOUSE_MOVE: lambda: [],
- EventTriggers.ON_MOUSE_OUT: lambda: [],
- EventTriggers.ON_MOUSE_OVER: lambda: [],
- EventTriggers.ON_MOUSE_UP: lambda: [],
- EventTriggers.ON_SCROLL: lambda: [],
- EventTriggers.ON_MOUNT: lambda: [],
- EventTriggers.ON_UNMOUNT: lambda: [],
+ EventTriggers.ON_FOCUS: empty_event,
+ EventTriggers.ON_BLUR: empty_event,
+ EventTriggers.ON_CLICK: empty_event,
+ EventTriggers.ON_CONTEXT_MENU: empty_event,
+ EventTriggers.ON_DOUBLE_CLICK: empty_event,
+ EventTriggers.ON_MOUSE_DOWN: empty_event,
+ EventTriggers.ON_MOUSE_ENTER: empty_event,
+ EventTriggers.ON_MOUSE_LEAVE: empty_event,
+ EventTriggers.ON_MOUSE_MOVE: empty_event,
+ EventTriggers.ON_MOUSE_OUT: empty_event,
+ EventTriggers.ON_MOUSE_OVER: empty_event,
+ EventTriggers.ON_MOUSE_UP: empty_event,
+ EventTriggers.ON_SCROLL: empty_event,
+ EventTriggers.ON_MOUNT: empty_event,
+ EventTriggers.ON_UNMOUNT: empty_event,
}
+
# Look for component specific triggers,
# e.g. variable declared as EventHandler types.
for field in self.get_fields().values():
- if types._issubclass(field.type_, EventHandler):
+ if types._issubclass(field.outer_type_, EventHandler):
args_spec = None
annotation = field.annotation
- if hasattr(annotation, "__metadata__"):
- args_spec = annotation.__metadata__[0]
- default_triggers[field.name] = args_spec or (lambda: [])
+ if (metadata := getattr(annotation, "__metadata__", None)) is not None:
+ args_spec = metadata[0]
+ default_triggers[field.name] = args_spec or (empty_event) # type: ignore
return default_triggers
def __repr__(self) -> str:
@@ -605,27 +683,6 @@ class Component(BaseComponent, ABC):
return _compile_component(self)
- def _apply_theme(self, theme: Optional[Component]):
- """Apply the theme to this component.
-
- Deprecated. Use add_style instead.
-
- Args:
- theme: The theme to apply.
- """
- pass
-
- def apply_theme(self, theme: Optional[Component]):
- """Apply a theme to the component and its children.
-
- Args:
- theme: The theme to apply.
- """
- self._apply_theme(theme)
- for child in self.children:
- if isinstance(child, Component):
- child.apply_theme(theme)
-
def _exclude_props(self) -> list[str]:
"""Props to exclude when adding the component props to the Tag.
@@ -645,7 +702,7 @@ class Component(BaseComponent, ABC):
"""
# Create the base tag.
tag = Tag(
- name=self.tag if not self.alias else self.alias,
+ name=(self.tag if not self.alias else self.alias) or "",
special_props=self.special_props,
)
@@ -659,7 +716,7 @@ class Component(BaseComponent, ABC):
# Add ref to element if `id` is not None.
ref = self.get_ref()
if ref is not None:
- props["ref"] = Var.create(ref, _var_is_local=False)
+ props["ref"] = Var(_js_expr=ref)
else:
props = props.copy()
@@ -733,22 +790,6 @@ class Component(BaseComponent, ABC):
from reflex.components.base.fragment import Fragment
from reflex.utils.exceptions import ComponentTypeError
- # Translate deprecated props to new names.
- new_prop_names = [
- prop for prop in cls.get_props() if prop in ["type", "min", "max"]
- ]
- for prop in new_prop_names:
- under_prop = f"{prop}_"
- if under_prop in props:
- console.deprecate(
- f"Underscore suffix for prop `{under_prop}`",
- reason=f"for consistency. Use `{prop}` instead.",
- deprecation_version="0.4.0",
- removal_version="0.6.0",
- dedupe=False,
- )
- props[prop] = props.pop(under_prop)
-
# Filter out None props
props = {key: value for key, value in props.items() if value is not None}
@@ -774,7 +815,7 @@ class Component(BaseComponent, ABC):
else (
Fragment.create(*child)
if isinstance(child, tuple)
- else Bare.create(contents=Var.create(child, _var_is_string=True))
+ else Bare.create(contents=LiteralVar.create(child))
)
)
for child in children
@@ -865,17 +906,6 @@ class Component(BaseComponent, ABC):
new_style.update(component_style)
style_vars.append(component_style._var_data)
- # 3. User-defined style from `Component.style`.
- # Apply theme for retro-compatibility with deprecated _apply_theme API
- if type(self)._apply_theme != Component._apply_theme:
- console.deprecate(
- f"{self.__class__.__name__}._apply_theme",
- reason="use add_style instead",
- deprecation_version="0.5.0",
- removal_version="0.6.0",
- )
- self._apply_theme(theme)
-
# 4. style dict and css props passed to the component instance.
new_style.update(self.style)
style_vars.append(self.style._var_data)
@@ -901,7 +931,12 @@ class Component(BaseComponent, ABC):
"""
if isinstance(self.style, Var):
return {"css": self.style}
- return {"css": Var.create(format_as_emotion(self.style))}
+ emotion_style = format_as_emotion(self.style)
+ return (
+ {"css": LiteralVar.create(emotion_style)}
+ if emotion_style is not None
+ else {}
+ )
def render(self) -> Dict:
"""Render the component.
@@ -994,10 +1029,10 @@ class Component(BaseComponent, ABC):
f"The component `{comp_name}` only allows the components: {valid_child_list} as children. Got `{child_name}` instead."
)
- if child._valid_parents and comp_name not in [
- *child._valid_parents,
- *allowed_components,
- ]:
+ if child._valid_parents and all(
+ clz_name not in [*child._valid_parents, *allowed_components]
+ for clz_name in self._iter_parent_classes_names()
+ ):
valid_parent_list = ", ".join(
[f"`{v_parent}`" for v_parent in child._valid_parents]
)
@@ -1026,8 +1061,11 @@ class Component(BaseComponent, ABC):
elif isinstance(event, EventChain):
event_args = []
for spec in event.events:
- for args in spec.args:
- event_args.extend(args)
+ if isinstance(spec, EventSpec):
+ for args in spec.args:
+ event_args.extend(args)
+ else:
+ event_args.append(spec)
yield event_trigger, event_args
def _get_vars(self, include_children: bool = False) -> list[Var]:
@@ -1056,10 +1094,10 @@ class Component(BaseComponent, ABC):
# Style keeps track of its own VarData instance, so embed in a temp Var that is yielded.
if isinstance(self.style, dict) and self.style or isinstance(self.style, Var):
vars.append(
- BaseVar(
- _var_name="style",
+ Var(
+ _js_expr="style",
_var_type=str,
- _var_data=self.style._var_data,
+ _var_data=VarData.merge(self.style._var_data),
)
)
@@ -1078,8 +1116,8 @@ class Component(BaseComponent, ABC):
vars.append(comp_prop)
elif isinstance(comp_prop, str):
# Collapse VarData encoded in f-strings.
- var = Var.create_safe(comp_prop)
- if var._var_data is not None:
+ var = LiteralVar.create(comp_prop)
+ if var._get_all_var_data() is not None:
vars.append(var)
# Get Vars associated with children.
@@ -1087,24 +1125,56 @@ class Component(BaseComponent, ABC):
for child in self.children:
if not isinstance(child, Component):
continue
- vars.extend(child._get_vars(include_children=include_children))
+ child_vars = child._get_vars(include_children=include_children)
+ vars.extend(child_vars)
return vars
- def _has_event_triggers(self) -> bool:
- """Check if the component or children have any event triggers.
+ def _event_trigger_values_use_state(self) -> bool:
+ """Check if the values of a component's event trigger use state.
Returns:
- True if the component or children have any event triggers.
+ True if any of the component's event trigger values uses State.
"""
- if self.event_triggers:
+ for trigger in self.event_triggers.values():
+ if isinstance(trigger, EventChain):
+ for event in trigger.events:
+ if isinstance(event, EventCallback):
+ continue
+ if isinstance(event, EventSpec):
+ if event.handler.state_full_name:
+ return True
+ else:
+ if event._var_state:
+ return True
+ elif isinstance(trigger, Var) and trigger._var_state:
+ return True
+ return False
+
+ def _has_stateful_event_triggers(self):
+ """Check if component or children have any event triggers that use state.
+
+ Returns:
+ True if the component or children have any event triggers that uses state.
+ """
+ if self.event_triggers and self._event_trigger_values_use_state():
return True
else:
for child in self.children:
- if isinstance(child, Component) and child._has_event_triggers():
+ if (
+ isinstance(child, Component)
+ and child._has_stateful_event_triggers()
+ ):
return True
return False
+ @classmethod
+ def _iter_parent_classes_names(cls) -> Iterator[str]:
+ for clz in cls.mro():
+ if clz is Component:
+ break
+ yield clz.__name__
+
@classmethod
def _iter_parent_classes_with_method(cls, method: str) -> Iterator[Type[Component]]:
"""Iterate through parent classes that define a given method.
@@ -1196,7 +1266,7 @@ class Component(BaseComponent, ABC):
# Return the dynamic imports
return dynamic_imports
- def _get_props_imports(self) -> List[str]:
+ def _get_props_imports(self) -> List[ParsedImportDict]:
"""Get the imports needed for components props.
Returns:
@@ -1222,7 +1292,7 @@ class Component(BaseComponent, ABC):
or format.format_library_name(dep or "") in self.transpile_packages
)
- def _get_dependencies_imports(self) -> imports.ImportDict:
+ def _get_dependencies_imports(self) -> ParsedImportDict:
"""Get the imports from lib_dependencies for installing.
Returns:
@@ -1239,7 +1309,7 @@ class Component(BaseComponent, ABC):
for dep in self.lib_dependencies
}
- def _get_hooks_imports(self) -> imports.ImportDict:
+ def _get_hooks_imports(self) -> ParsedImportDict:
"""Get the imports required by certain hooks.
Returns:
@@ -1250,7 +1320,9 @@ class Component(BaseComponent, ABC):
if self._get_ref_hook():
# Handle hooks needed for attaching react refs to DOM nodes.
_imports.setdefault("react", set()).add(ImportVar(tag="useRef"))
- _imports.setdefault(f"/{Dirs.STATE_PATH}", set()).add(ImportVar(tag="refs"))
+ _imports.setdefault(f"$/{Dirs.STATE_PATH}", set()).add(
+ ImportVar(tag="refs")
+ )
if self._get_mount_lifecycle_hook():
# Handle hooks for `on_mount` / `on_unmount`.
@@ -1265,13 +1337,22 @@ class Component(BaseComponent, ABC):
},
)
+ other_imports = []
user_hooks = self._get_hooks()
- if user_hooks is not None and isinstance(user_hooks, Var):
- _imports = imports.merge_imports(_imports, user_hooks._var_data.imports) # type: ignore
+ user_hooks_data = (
+ VarData.merge(user_hooks._get_all_var_data())
+ if user_hooks is not None and isinstance(user_hooks, Var)
+ else None
+ )
+ if user_hooks_data is not None:
+ other_imports.append(user_hooks_data.imports)
+ other_imports.extend(
+ hook_imports for hook_imports in self._get_added_hooks().values()
+ )
- return _imports
+ return imports.merge_imports(_imports, *other_imports)
- def _get_imports(self) -> imports.ImportDict:
+ def _get_imports(self) -> ParsedImportDict:
"""Get all the libraries and fields that are used by the component.
Returns:
@@ -1287,29 +1368,26 @@ class Component(BaseComponent, ABC):
event_imports = Imports.EVENTS if self.event_triggers else {}
# Collect imports from Vars used directly by this component.
- var_imports = [
- var._var_data.imports for var in self._get_vars() if var._var_data
- ]
-
- # If any subclass implements add_imports, merge the imports.
- def _make_list(
- value: str | ImportVar | list[str | ImportVar],
- ) -> list[str | ImportVar]:
- if isinstance(value, (str, ImportVar)):
- return [value]
- return value
-
- _added_import_dicts = []
- for clz in self._iter_parent_classes_with_method("add_imports"):
- _added_import_dicts.append(
- {
- package: [
- ImportVar(tag=tag) if not isinstance(tag, ImportVar) else tag
- for tag in _make_list(maybe_tags)
- ]
- for package, maybe_tags in clz.add_imports(self).items()
- }
+ var_datas = [var._get_all_var_data() for var in self._get_vars()]
+ var_imports: List[ImmutableParsedImportDict] = list(
+ map(
+ lambda var_data: var_data.imports,
+ filter(
+ None,
+ var_datas,
+ ),
)
+ )
+
+ added_import_dicts: list[ParsedImportDict] = []
+ for clz in self._iter_parent_classes_with_method("add_imports"):
+ list_of_import_dict = clz.add_imports(self)
+
+ if not isinstance(list_of_import_dict, list):
+ list_of_import_dict = [list_of_import_dict]
+
+ for import_dict in list_of_import_dict:
+ added_import_dicts.append(parse_imports(import_dict))
return imports.merge_imports(
*self._get_props_imports(),
@@ -1318,10 +1396,10 @@ class Component(BaseComponent, ABC):
_imports,
event_imports,
*var_imports,
- *_added_import_dicts,
+ *added_import_dicts,
)
- def _get_all_imports(self, collapse: bool = False) -> imports.ImportDict:
+ def _get_all_imports(self, collapse: bool = False) -> ParsedImportDict:
"""Get all the libraries and fields that are used by the component and its children.
Args:
@@ -1346,9 +1424,9 @@ class Component(BaseComponent, ABC):
on_mount = self.event_triggers.get(EventTriggers.ON_MOUNT, None)
on_unmount = self.event_triggers.get(EventTriggers.ON_UNMOUNT, None)
if on_mount is not None:
- on_mount = format.format_event_chain(on_mount)
+ on_mount = str(LiteralVar.create(on_mount)) + "()"
if on_unmount is not None:
- on_unmount = format.format_event_chain(on_unmount)
+ on_unmount = str(LiteralVar.create(on_unmount)) + "()"
if on_mount is not None or on_unmount is not None:
return f"""
useEffect(() => {{
@@ -1366,7 +1444,7 @@ class Component(BaseComponent, ABC):
"""
ref = self.get_ref()
if ref is not None:
- return f"const {ref} = useRef(null); {str(Var.create_safe(ref).as_ref())} = {ref};"
+ return f"const {ref} = useRef(null); {str(Var(_js_expr=ref).as_ref())} = {ref};"
def _get_vars_hooks(self) -> dict[str, None]:
"""Get the hooks required by vars referenced in this component.
@@ -1376,8 +1454,13 @@ class Component(BaseComponent, ABC):
"""
vars_hooks = {}
for var in self._get_vars():
- if var._var_data:
- vars_hooks.update(var._var_data.hooks)
+ var_data = var._get_all_var_data()
+ if var_data is not None:
+ vars_hooks.update(
+ var_data.hooks
+ if isinstance(var_data.hooks, dict)
+ else {k: None for k in var_data.hooks}
+ )
return vars_hooks
def _get_events_hooks(self) -> dict[str, None]:
@@ -1416,6 +1499,38 @@ class Component(BaseComponent, ABC):
**self._get_special_hooks(),
}
+ def _get_added_hooks(self) -> dict[str, ImportDict]:
+ """Get the hooks added via `add_hooks` method.
+
+ Returns:
+ The deduplicated hooks and imports added by the component and parent components.
+ """
+ code = {}
+
+ def extract_var_hooks(hook: Var):
+ _imports = {}
+ var_data = VarData.merge(hook._get_all_var_data())
+ if var_data is not None:
+ for sub_hook in var_data.hooks:
+ code[sub_hook] = {}
+ if var_data.imports:
+ _imports = var_data.imports
+ if str(hook) in code:
+ code[str(hook)] = imports.merge_imports(code[str(hook)], _imports)
+ else:
+ code[str(hook)] = _imports
+
+ # Add the hook code from add_hooks for each parent class (this is reversed to preserve
+ # the order of the hooks in the final output)
+ for clz in reversed(tuple(self._iter_parent_classes_with_method("add_hooks"))):
+ for hook in clz.add_hooks(self):
+ if isinstance(hook, Var):
+ extract_var_hooks(hook)
+ else:
+ code[hook] = {}
+
+ return code
+
def _get_hooks(self) -> str | None:
"""Get the React hooks for this component.
@@ -1454,11 +1569,8 @@ class Component(BaseComponent, ABC):
if hooks is not None:
code[hooks] = None
- # Add the hook code from add_hooks for each parent class (this is reversed to preserve
- # the order of the hooks in the final output)
- for clz in reversed(tuple(self._iter_parent_classes_with_method("add_hooks"))):
- for hook in clz.add_hooks(self):
- code[hook] = None
+ for hook in self._get_added_hooks():
+ code[hook] = None
# Add the hook code for the children.
for child in self.children:
@@ -1473,7 +1585,7 @@ class Component(BaseComponent, ABC):
The ref name.
"""
# do not create a ref if the id is dynamic or unspecified
- if self.id is None or isinstance(self.id, BaseVar):
+ if self.id is None or isinstance(self.id, Var):
return None
return format.format_ref(self.id)
@@ -1567,7 +1679,7 @@ class CustomComponent(Component):
"""A custom user-defined component."""
# Use the components library.
- library = f"/{Dirs.COMPONENTS_PATH}"
+ library = f"$/{Dirs.COMPONENTS_PATH}"
# The function that creates the component.
component_fn: Callable[..., Component] = Component.create
@@ -1611,15 +1723,16 @@ class CustomComponent(Component):
value = self._create_event_chain(
value=value,
args_spec=event_triggers_in_component_declaration.get(
- key, lambda: []
+ key, empty_event
),
+ key=key,
)
self.props[format.to_camel_case(key)] = value
continue
# Handle subclasses of Base.
if isinstance(value, Base):
- base_value = Var.create(value)
+ base_value = LiteralVar.create(value)
# Track hooks and imports associated with Component instances.
if base_value is not None and isinstance(value, Component):
@@ -1633,7 +1746,7 @@ class CustomComponent(Component):
else:
value = base_value
else:
- value = Var.create(value, _var_is_string=isinstance(value, str))
+ value = LiteralVar.create(value)
# Set the prop.
self.props[format.to_camel_case(key)] = value
@@ -1674,10 +1787,14 @@ class CustomComponent(Component):
Args:
seen: The tags of the components that have already been seen.
+ Raises:
+ ValueError: If the tag is not set.
+
Returns:
The set of custom components.
"""
- assert self.tag is not None, "The tag must be set."
+ if self.tag is None:
+ raise ValueError("The tag must be set.")
# Store the seen components in a set to avoid infinite recursion.
if seen is None:
@@ -1712,19 +1829,19 @@ class CustomComponent(Component):
"""
return super()._render(props=self.props)
- def get_prop_vars(self) -> List[BaseVar]:
+ def get_prop_vars(self) -> List[Var]:
"""Get the prop vars.
Returns:
The prop vars.
"""
return [
- BaseVar(
- _var_name=name,
+ Var(
+ _js_expr=name,
_var_type=(
prop._var_type if types._isinstance(prop, Var) else type(prop)
),
- )
+ ).guess_type()
for name, prop in self.props.items()
]
@@ -1737,9 +1854,11 @@ class CustomComponent(Component):
Returns:
Each var referenced by the component (props, styles, event handlers).
"""
- return super()._get_vars(include_children=include_children) + [
- prop for prop in self.props.values() if isinstance(prop, Var)
- ]
+ return (
+ super()._get_vars(include_children=include_children)
+ + [prop for prop in self.props.values() if isinstance(prop, Var)]
+ + self.get_component(self)._get_vars(include_children=include_children)
+ )
@lru_cache(maxsize=None) # noqa
def get_component(self) -> Component:
@@ -1779,7 +1898,7 @@ memo = custom_component
class NoSSRComponent(Component):
"""A dynamic component that is not rendered on the server."""
- def _get_imports(self) -> imports.ImportDict:
+ def _get_imports(self) -> ParsedImportDict:
"""Get the imports for the component.
Returns:
@@ -1824,19 +1943,6 @@ class NoSSRComponent(Component):
return "".join((library_import, mod_import, opts_fragment))
-@serializer
-def serialize_component(comp: Component):
- """Serialize a component.
-
- Args:
- comp: The component to serialize.
-
- Returns:
- The serialized component.
- """
- return str(comp)
-
-
class StatefulComponent(BaseComponent):
"""A component that depends on state and is rendered outside of the page component.
@@ -1893,7 +1999,7 @@ class StatefulComponent(BaseComponent):
if not should_memoize:
# Determine if any Vars have associated data.
for prop_var in component._get_vars():
- if prop_var._var_data:
+ if prop_var._get_all_var_data():
should_memoize = True
break
@@ -1908,7 +2014,7 @@ class StatefulComponent(BaseComponent):
should_memoize = True
break
child = cls._child_var(child)
- if isinstance(child, Var) and child._var_data:
+ if isinstance(child, Var) and child._get_all_var_data():
should_memoize = True
break
@@ -1958,6 +2064,7 @@ class StatefulComponent(BaseComponent):
from reflex.components.base.bare import Bare
from reflex.components.core.cond import Cond
from reflex.components.core.foreach import Foreach
+ from reflex.components.core.match import Match
if isinstance(child, Bare):
return child.contents
@@ -1965,6 +2072,8 @@ class StatefulComponent(BaseComponent):
return child.cond
if isinstance(child, Foreach):
return child.iterable
+ if isinstance(child, Match):
+ return child.cond
return child
@classmethod
@@ -2041,10 +2150,20 @@ class StatefulComponent(BaseComponent):
Returns:
A list of var names created by the hook declaration.
"""
- var_name = hook.partition("=")[0].strip().split(None, 1)[1].strip()
- if var_name.startswith("["):
- # Break up array destructuring.
- return [v.strip() for v in var_name.strip("[]").split(",")]
+ # Ensure that the hook is a var declaration.
+ var_decl = hook.partition("=")[0].strip()
+ if not any(var_decl.startswith(kw) for kw in ["const ", "let ", "var "]):
+ return []
+
+ # Extract the var name from the declaration.
+ _, _, var_name = var_decl.partition(" ")
+ var_name = var_name.strip()
+
+ # Break up array and object destructuring if used.
+ if var_name.startswith("[") or var_name.startswith("{"):
+ return [
+ v.strip().replace("...", "") for v in var_name.strip("[]{}").split(",")
+ ]
return [var_name]
@classmethod
@@ -2075,9 +2194,7 @@ class StatefulComponent(BaseComponent):
# Get the actual EventSpec and render it.
event = component.event_triggers[event_trigger]
- rendered_chain = format.format_prop(event)
- if isinstance(rendered_chain, str):
- rendered_chain = rendered_chain.strip("{}")
+ rendered_chain = str(LiteralVar.create(event))
# Hash the rendered EventChain to get a deterministic function name.
chain_hash = md5(str(rendered_chain).encode("utf-8")).hexdigest()
@@ -2086,20 +2203,21 @@ class StatefulComponent(BaseComponent):
# Calculate Var dependencies accessed by the handler for useCallback dep array.
var_deps = ["addEvents", "Event"]
for arg in event_args:
- if arg._var_data is None:
+ var_data = arg._get_all_var_data()
+ if var_data is None:
continue
- for hook in arg._var_data.hooks:
+ for hook in var_data.hooks:
var_deps.extend(cls._get_hook_deps(hook))
memo_var_data = VarData.merge(
- *[var._var_data for var in event_args],
- VarData( # type: ignore
- imports={"react": {ImportVar(tag="useCallback")}},
+ *[var._get_all_var_data() for var in event_args],
+ VarData(
+ imports={"react": [ImportVar(tag="useCallback")]},
),
)
# Store the memoized function name and hook code for this event trigger.
trigger_memo[event_trigger] = (
- Var.create_safe(memo_name)._replace(
+ Var(_js_expr=memo_name)._replace(
_var_type=EventChain, merge_var_data=memo_var_data
),
f"const {memo_name} = useCallback({rendered_chain}, [{', '.join(var_deps)}])",
@@ -2122,7 +2240,7 @@ class StatefulComponent(BaseComponent):
"""
return {}
- def _get_all_imports(self) -> imports.ImportDict:
+ def _get_all_imports(self) -> ParsedImportDict:
"""Get all the libraries and fields that are used by the component.
Returns:
@@ -2130,7 +2248,7 @@ class StatefulComponent(BaseComponent):
"""
if self.rendered_as_shared:
return {
- f"/{Dirs.UTILS}/{PageNames.STATEFUL_COMPONENTS}": [
+ f"$/{Dirs.UTILS}/{PageNames.STATEFUL_COMPONENTS}": [
ImportVar(tag=self.tag)
]
}
@@ -2172,7 +2290,7 @@ class StatefulComponent(BaseComponent):
Returns:
The tag to render.
"""
- return dict(Tag(name=self.tag))
+ return dict(Tag(name=self.tag or ""))
def __str__(self) -> str:
"""Represent the component in React.
@@ -2237,3 +2355,206 @@ class MemoizationLeaf(Component):
update={"disposition": MemoizationDisposition.ALWAYS}
)
return comp
+
+
+load_dynamic_serializer()
+
+
+class ComponentVar(Var[Component], python_types=BaseComponent):
+ """A Var that represents a Component."""
+
+
+def empty_component() -> Component:
+ """Create an empty component.
+
+ Returns:
+ An empty component.
+ """
+ from reflex.components.base.bare import Bare
+
+ return Bare.create("")
+
+
+def render_dict_to_var(tag: dict | Component | str, imported_names: set[str]) -> Var:
+ """Convert a render dict to a Var.
+
+ Args:
+ tag: The render dict.
+ imported_names: The names of the imported components.
+
+ Returns:
+ The Var.
+ """
+ if not isinstance(tag, dict):
+ if isinstance(tag, Component):
+ return render_dict_to_var(tag.render(), imported_names)
+ return Var.create(tag)
+
+ if "iterable" in tag:
+ function_return = Var.create(
+ [
+ render_dict_to_var(child.render(), imported_names)
+ for child in tag["children"]
+ ]
+ )
+
+ func = ArgsFunctionOperation.create(
+ (tag["arg_var_name"], tag["index_var_name"]),
+ function_return,
+ )
+
+ return FunctionStringVar.create("Array.prototype.map.call").call(
+ tag["iterable"]
+ if not isinstance(tag["iterable"], ObjectVar)
+ else tag["iterable"].items(),
+ func,
+ )
+
+ if tag["name"] == "match":
+ element = tag["cond"]
+
+ conditionals = tag["default"]
+
+ for case in tag["match_cases"][::-1]:
+ condition = case[0].to_string() == element.to_string()
+ for pattern in case[1:-1]:
+ condition = condition | (pattern.to_string() == element.to_string())
+
+ conditionals = ternary_operation(
+ condition,
+ case[-1],
+ conditionals,
+ )
+
+ return conditionals
+
+ if "cond" in tag:
+ return ternary_operation(
+ tag["cond"],
+ render_dict_to_var(tag["true_value"], imported_names),
+ render_dict_to_var(tag["false_value"], imported_names)
+ if tag["false_value"] is not None
+ else Var.create(None),
+ )
+
+ props = {}
+
+ special_props = []
+
+ for prop_str in tag["props"]:
+ if "=" not in prop_str:
+ special_props.append(Var(prop_str).to(ObjectVar))
+ continue
+ prop = prop_str.index("=")
+ key = prop_str[:prop]
+ value = prop_str[prop + 2 : -1]
+ props[key] = value
+
+ props = Var.create({Var.create(k): Var(v) for k, v in props.items()})
+
+ for prop in special_props:
+ props = props.merge(prop)
+
+ contents = tag["contents"][1:-1] if tag["contents"] else None
+
+ raw_tag_name = tag.get("name")
+ tag_name = Var(raw_tag_name or "Fragment")
+
+ tag_name = (
+ Var.create(raw_tag_name)
+ if raw_tag_name
+ and raw_tag_name.split(".")[0] not in imported_names
+ and raw_tag_name.lower() == raw_tag_name
+ else tag_name
+ )
+
+ return FunctionStringVar.create(
+ "jsx",
+ ).call(
+ tag_name,
+ props,
+ *([Var(contents)] if contents is not None else []),
+ *[render_dict_to_var(child, imported_names) for child in tag["children"]],
+ )
+
+
+@dataclasses.dataclass(
+ eq=False,
+ frozen=True,
+)
+class LiteralComponentVar(CachedVarOperation, LiteralVar, ComponentVar):
+ """A Var that represents a Component."""
+
+ _var_value: BaseComponent = dataclasses.field(default_factory=empty_component)
+
+ @cached_property_no_lock
+ def _cached_var_name(self) -> str:
+ """Get the name of the var.
+
+ Returns:
+ The name of the var.
+ """
+ var_data = self._get_all_var_data()
+ if var_data is not None:
+ # flatten imports
+ imported_names = {j.alias or j.name for i in var_data.imports for j in i[1]}
+ else:
+ imported_names = set()
+ return str(render_dict_to_var(self._var_value.render(), imported_names))
+
+ @cached_property_no_lock
+ def _cached_get_all_var_data(self) -> VarData | None:
+ """Get the VarData for the var.
+
+ Returns:
+ The VarData for the var.
+ """
+ return VarData.merge(
+ VarData(
+ imports={
+ "@emotion/react": [
+ ImportVar(tag="jsx"),
+ ],
+ }
+ ),
+ VarData(
+ imports=self._var_value._get_all_imports(),
+ ),
+ VarData(
+ imports={
+ "react": [
+ ImportVar(tag="Fragment"),
+ ],
+ }
+ ),
+ )
+
+ def __hash__(self) -> int:
+ """Get the hash of the var.
+
+ Returns:
+ The hash of the var.
+ """
+ return hash((self.__class__.__name__, self._js_expr))
+
+ @classmethod
+ def create(
+ cls,
+ value: Component,
+ _var_data: VarData | None = None,
+ ):
+ """Create a var from a value.
+
+ Args:
+ value: The value of the var.
+ _var_data: Additional hooks and imports associated with the Var.
+
+ Returns:
+ The var.
+ """
+ return LiteralComponentVar(
+ _js_expr="",
+ _var_type=type(value),
+ _var_data=_var_data,
+ _var_value=value,
+ )
diff --git a/reflex/components/core/__init__.py b/reflex/components/core/__init__.py
index 80c73add8..fbe0bdc84 100644
--- a/reflex/components/core/__init__.py
+++ b/reflex/components/core/__init__.py
@@ -1,34 +1,57 @@
"""Core Reflex components."""
-from . import layout as layout
-from .banner import ConnectionBanner, ConnectionModal, ConnectionPulser
-from .colors import color
-from .cond import Cond, color_mode_cond, cond
-from .debounce import DebounceInput
-from .foreach import Foreach
-from .html import Html
-from .match import Match
-from .responsive import (
- desktop_only,
- mobile_and_tablet,
- mobile_only,
- tablet_and_desktop,
- tablet_only,
-)
-from .upload import (
- UploadNamespace,
- cancel_upload,
- clear_selected_files,
- get_upload_dir,
- get_upload_url,
- selected_files,
-)
+from __future__ import annotations
-connection_banner = ConnectionBanner.create
-connection_modal = ConnectionModal.create
-connection_pulser = ConnectionPulser.create
-debounce_input = DebounceInput.create
-foreach = Foreach.create
-html = Html.create
-match = Match.create
-upload = UploadNamespace()
+from reflex.utils import lazy_loader
+
+_SUBMODULES: set[str] = {"layout"}
+
+_SUBMOD_ATTRS: dict[str, list[str]] = {
+ "banner": [
+ "ConnectionBanner",
+ "ConnectionModal",
+ "ConnectionPulser",
+ "ConnectionToaster",
+ "connection_banner",
+ "connection_modal",
+ "connection_toaster",
+ "connection_pulser",
+ ],
+ "clipboard": ["Clipboard", "clipboard"],
+ "colors": [
+ "color",
+ ],
+ "cond": ["Cond", "color_mode_cond", "cond"],
+ "debounce": ["DebounceInput", "debounce_input"],
+ "foreach": [
+ "foreach",
+ "Foreach",
+ ],
+ "html": ["html", "Html"],
+ "match": [
+ "match",
+ "Match",
+ ],
+ "breakpoints": ["breakpoints", "set_breakpoints"],
+ "responsive": [
+ "desktop_only",
+ "mobile_and_tablet",
+ "mobile_only",
+ "tablet_and_desktop",
+ "tablet_only",
+ ],
+ "upload": [
+ "upload",
+ "cancel_upload",
+ "clear_selected_files",
+ "get_upload_dir",
+ "get_upload_url",
+ "selected_files",
+ ],
+}
+
+__getattr__, __dir__, __all__ = lazy_loader.attach(
+ __name__,
+ submodules=_SUBMODULES,
+ submod_attrs=_SUBMOD_ATTRS,
+)
diff --git a/reflex/components/core/__init__.pyi b/reflex/components/core/__init__.pyi
new file mode 100644
index 000000000..ea9275334
--- /dev/null
+++ b/reflex/components/core/__init__.pyi
@@ -0,0 +1,41 @@
+"""Stub file for reflex/components/core/__init__.py"""
+# ------------------- DO NOT EDIT ----------------------
+# This file was generated by `reflex/utils/pyi_generator.py`!
+# ------------------------------------------------------
+
+from . import layout as layout
+from .banner import ConnectionBanner as ConnectionBanner
+from .banner import ConnectionModal as ConnectionModal
+from .banner import ConnectionPulser as ConnectionPulser
+from .banner import ConnectionToaster as ConnectionToaster
+from .banner import connection_banner as connection_banner
+from .banner import connection_modal as connection_modal
+from .banner import connection_pulser as connection_pulser
+from .banner import connection_toaster as connection_toaster
+from .breakpoints import breakpoints as breakpoints
+from .breakpoints import set_breakpoints as set_breakpoints
+from .clipboard import Clipboard as Clipboard
+from .clipboard import clipboard as clipboard
+from .colors import color as color
+from .cond import Cond as Cond
+from .cond import color_mode_cond as color_mode_cond
+from .cond import cond as cond
+from .debounce import DebounceInput as DebounceInput
+from .debounce import debounce_input as debounce_input
+from .foreach import Foreach as Foreach
+from .foreach import foreach as foreach
+from .html import Html as Html
+from .html import html as html
+from .match import Match as Match
+from .match import match as match
+from .responsive import desktop_only as desktop_only
+from .responsive import mobile_and_tablet as mobile_and_tablet
+from .responsive import mobile_only as mobile_only
+from .responsive import tablet_and_desktop as tablet_and_desktop
+from .responsive import tablet_only as tablet_only
+from .upload import cancel_upload as cancel_upload
+from .upload import clear_selected_files as clear_selected_files
+from .upload import get_upload_dir as get_upload_dir
+from .upload import get_upload_url as get_upload_url
+from .upload import selected_files as selected_files
+from .upload import upload as upload
diff --git a/reflex/components/core/banner.py b/reflex/components/core/banner.py
index 0c781fba8..8a37b0bf7 100644
--- a/reflex/components/core/banner.py
+++ b/reflex/components/core/banner.py
@@ -4,7 +4,6 @@ from __future__ import annotations
from typing import Optional
-from reflex.components.base.bare import Bare
from reflex.components.component import Component
from reflex.components.core.cond import cond
from reflex.components.el.elements.typography import Div
@@ -14,57 +13,65 @@ from reflex.components.radix.themes.components.dialog import (
DialogRoot,
DialogTitle,
)
-from reflex.components.radix.themes.layout import Flex
+from reflex.components.radix.themes.layout.flex import Flex
from reflex.components.radix.themes.typography.text import Text
+from reflex.components.sonner.toast import Toaster, ToastProps
from reflex.constants import Dirs, Hooks, Imports
-from reflex.utils import imports
-from reflex.vars import Var, VarData
+from reflex.constants.compiler import CompileVars
+from reflex.utils.imports import ImportVar
+from reflex.vars import VarData
+from reflex.vars.base import LiteralVar, Var
+from reflex.vars.function import FunctionStringVar
+from reflex.vars.number import BooleanVar
+from reflex.vars.sequence import LiteralArrayVar
connect_error_var_data: VarData = VarData( # type: ignore
imports=Imports.EVENTS,
hooks={Hooks.EVENTS: None},
)
-connection_error: Var = Var.create_safe(
- value="(connectErrors.length > 0) ? connectErrors[connectErrors.length - 1].message : ''",
- _var_is_local=False,
- _var_is_string=False,
-)._replace(merge_var_data=connect_error_var_data)
+connect_errors = Var(
+ _js_expr=CompileVars.CONNECT_ERROR, _var_data=connect_error_var_data
+)
-connection_errors_count: Var = Var.create_safe(
- value="connectErrors.length",
- _var_is_string=False,
- _var_is_local=False,
-)._replace(merge_var_data=connect_error_var_data)
+connection_error = Var(
+ _js_expr="((connectErrors.length > 0) ? connectErrors[connectErrors.length - 1].message : '')",
+ _var_data=connect_error_var_data,
+)
-has_connection_errors: Var = Var.create_safe(
- value="connectErrors.length > 0",
- _var_is_string=False,
-)._replace(_var_type=bool, merge_var_data=connect_error_var_data)
+connection_errors_count = Var(
+ _js_expr="connectErrors.length", _var_data=connect_error_var_data
+)
-has_too_many_connection_errors: Var = Var.create_safe(
- value="connectErrors.length >= 2",
- _var_is_string=False,
-)._replace(_var_type=bool, merge_var_data=connect_error_var_data)
+has_connection_errors = Var(
+ _js_expr="(connectErrors.length > 0)", _var_data=connect_error_var_data
+).to(BooleanVar)
+
+has_too_many_connection_errors = Var(
+ _js_expr="(connectErrors.length >= 2)", _var_data=connect_error_var_data
+).to(BooleanVar)
-class WebsocketTargetURL(Bare):
+class WebsocketTargetURL(Var):
"""A component that renders the websocket target URL."""
- def _get_imports(self) -> imports.ImportDict:
- return {
- f"/{Dirs.STATE_PATH}": [imports.ImportVar(tag="getBackendURL")],
- "/env.json": [imports.ImportVar(tag="env", is_default=True)],
- }
-
@classmethod
- def create(cls) -> Component:
+ def create(cls) -> Var:
"""Create a websocket target URL component.
Returns:
The websocket target URL component.
"""
- return super().create(contents="{getBackendURL(env.EVENT).href}")
+ return Var(
+ _js_expr="getBackendURL(env.EVENT).href",
+ _var_data=VarData(
+ imports={
+ "$/env.json": [ImportVar(tag="env", is_default=True)],
+ f"$/{Dirs.STATE_PATH}": [ImportVar(tag="getBackendURL")],
+ },
+ ),
+ _var_type=WebsocketTargetURL,
+ )
def default_connection_error() -> list[str | Var | Component]:
@@ -81,6 +88,80 @@ def default_connection_error() -> list[str | Var | Component]:
]
+class ConnectionToaster(Toaster):
+ """A connection toaster component."""
+
+ def add_hooks(self) -> list[str | Var]:
+ """Add the hooks for the connection toaster.
+
+ Returns:
+ The hooks for the connection toaster.
+ """
+ toast_id = "websocket-error"
+ target_url = WebsocketTargetURL.create()
+ props = ToastProps( # type: ignore
+ description=LiteralVar.create(
+ f"Check if server is reachable at {target_url}",
+ ),
+ close_button=True,
+ duration=120000,
+ id=toast_id,
+ )
+
+ individual_hooks = [
+ f"const toast_props = {str(LiteralVar.create(props))};",
+ f"const [userDismissed, setUserDismissed] = useState(false);",
+ FunctionStringVar(
+ "useEffect",
+ _var_data=VarData(
+ imports={
+ "react": ["useEffect", "useState"],
+ **dict(target_url._get_all_var_data().imports), # type: ignore
+ }
+ ),
+ ).call(
+ # TODO: This breaks the assumption that Vars are JS expressions
+ Var(
+ _js_expr=f"""
+() => {{
+ if ({str(has_too_many_connection_errors)}) {{
+ if (!userDismissed) {{
+ toast.error(
+ `Cannot connect to server: ${{{connection_error}}}.`,
+ {{...toast_props, onDismiss: () => setUserDismissed(true)}},
+ )
+ }}
+ }} else {{
+ toast.dismiss("{toast_id}");
+ setUserDismissed(false); // after reconnection reset dismissed state
+ }}
+}}
+"""
+ ),
+ LiteralArrayVar.create([connect_errors]),
+ ),
+ ]
+
+ return [
+ Hooks.EVENTS,
+ *individual_hooks,
+ ]
+
+ @classmethod
+ def create(cls, *children, **props) -> Component:
+ """Create a connection toaster component.
+
+ Args:
+ *children: The children of the component.
+ **props: The properties of the component.
+
+ Returns:
+ The connection toaster component.
+ """
+ Toaster.is_used = True
+ return super().create(*children, **props)
+
+
class ConnectionBanner(Component):
"""A connection banner component."""
@@ -143,32 +224,36 @@ class WifiOffPulse(Icon):
"""A wifi_off icon with an animated opacity pulse."""
@classmethod
- def create(cls, **props) -> Component:
+ def create(cls, *children, **props) -> Icon:
"""Create a wifi_off icon with an animated opacity pulse.
Args:
+ *children: The children of the component.
**props: The properties of the component.
Returns:
The icon component with default props applied.
"""
+ pulse_var = Var(_js_expr="pulse")
return super().create(
"wifi_off",
color=props.pop("color", "crimson"),
size=props.pop("size", 32),
z_index=props.pop("z_index", 9999),
position=props.pop("position", "fixed"),
- bottom=props.pop("botton", "30px"),
- right=props.pop("right", "30px"),
- animation=Var.create(f"${{pulse}} 1s infinite", _var_is_string=True),
+ bottom=props.pop("botton", "33px"),
+ right=props.pop("right", "33px"),
+ animation=LiteralVar.create(f"{pulse_var} 1s infinite"),
**props,
)
- def _get_imports(self) -> imports.ImportDict:
- return imports.merge_imports(
- super()._get_imports(),
- {"@emotion/react": [imports.ImportVar(tag="keyframes")]},
- )
+ def add_imports(self) -> dict[str, str | ImportVar | list[str | ImportVar]]:
+ """Add imports for the WifiOffPulse component.
+
+ Returns:
+ The import dict.
+ """
+ return {"@emotion/react": [ImportVar(tag="keyframes")]}
def _get_custom_code(self) -> str | None:
return """
@@ -201,7 +286,14 @@ class ConnectionPulser(Div):
has_connection_errors,
WifiOffPulse.create(**props),
),
+ title=f"Connection Error: {connection_error}",
position="fixed",
width="100vw",
height="0",
)
+
+
+connection_banner = ConnectionBanner.create
+connection_modal = ConnectionModal.create
+connection_toaster = ConnectionToaster.create
+connection_pulser = ConnectionPulser.create
diff --git a/reflex/components/core/banner.pyi b/reflex/components/core/banner.pyi
index 43fc53e29..7c2be272c 100644
--- a/reflex/components/core/banner.pyi
+++ b/reflex/components/core/banner.pyi
@@ -1,104 +1,142 @@
"""Stub file for reflex/components/core/banner.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Optional
-from reflex.components.base.bare import Bare
+
from reflex.components.component import Component
-from reflex.components.core.cond import cond
from reflex.components.el.elements.typography import Div
from reflex.components.lucide.icon import Icon
-from reflex.components.radix.themes.components.dialog import (
- DialogContent,
- DialogRoot,
- DialogTitle,
-)
-from reflex.components.radix.themes.layout import Flex
-from reflex.components.radix.themes.typography.text import Text
-from reflex.constants import Dirs, Hooks, Imports
-from reflex.utils import imports
-from reflex.vars import Var, VarData
+from reflex.components.sonner.toast import Toaster, ToastProps
+from reflex.constants.compiler import CompileVars
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.utils.imports import ImportVar
+from reflex.vars import VarData
+from reflex.vars.base import Var
+from reflex.vars.number import BooleanVar
connect_error_var_data: VarData
-connection_error: Var
-connection_errors_count: Var
-has_connection_errors: Var
-has_too_many_connection_errors: Var
+connect_errors = Var(
+ _js_expr=CompileVars.CONNECT_ERROR, _var_data=connect_error_var_data
+)
+connection_error = Var(
+ _js_expr="((connectErrors.length > 0) ? connectErrors[connectErrors.length - 1].message : '')",
+ _var_data=connect_error_var_data,
+)
+connection_errors_count = Var(
+ _js_expr="connectErrors.length", _var_data=connect_error_var_data
+)
+has_connection_errors = Var(
+ _js_expr="(connectErrors.length > 0)", _var_data=connect_error_var_data
+).to(BooleanVar)
+has_too_many_connection_errors = Var(
+ _js_expr="(connectErrors.length >= 2)", _var_data=connect_error_var_data
+).to(BooleanVar)
-class WebsocketTargetURL(Bare):
+class WebsocketTargetURL(Var):
+ @classmethod
+ def create(cls) -> Var: ... # type: ignore
+
+def default_connection_error() -> list[str | Var | Component]: ...
+
+class ConnectionToaster(Toaster):
+ def add_hooks(self) -> list[str | Var]: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- contents: Optional[Union[Var[str], str]] = None,
+ theme: Optional[Union[Var[str], str]] = None,
+ rich_colors: Optional[Union[Var[bool], bool]] = None,
+ expand: Optional[Union[Var[bool], bool]] = None,
+ visible_toasts: Optional[Union[Var[int], int]] = None,
+ position: Optional[
+ Union[
+ Literal[
+ "bottom-center",
+ "bottom-left",
+ "bottom-right",
+ "top-center",
+ "top-left",
+ "top-right",
+ ],
+ Var[
+ Literal[
+ "bottom-center",
+ "bottom-left",
+ "bottom-right",
+ "top-center",
+ "top-left",
+ "top-right",
+ ]
+ ],
+ ]
+ ] = None,
+ close_button: Optional[Union[Var[bool], bool]] = None,
+ offset: Optional[Union[Var[str], str]] = None,
+ dir: Optional[Union[Var[str], str]] = None,
+ hotkey: Optional[Union[Var[str], str]] = None,
+ invert: Optional[Union[Var[bool], bool]] = None,
+ toast_options: Optional[Union[ToastProps, Var[ToastProps]]] = None,
+ gap: Optional[Union[Var[int], int]] = None,
+ loading_icon: Optional[Union[Icon, Var[Icon]]] = None,
+ pause_when_page_is_hidden: Optional[Union[Var[bool], bool]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
- ) -> "WebsocketTargetURL":
- """Create a websocket target URL component.
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
+ ) -> "ConnectionToaster":
+ """Create a connection toaster component.
+
+ Args:
+ *children: The children of the component.
+ theme: the theme of the toast
+ rich_colors: whether to show rich colors
+ expand: whether to expand the toast
+ visible_toasts: the number of toasts that are currently visible
+ position: the position of the toast
+ close_button: whether to show the close button
+ offset: offset of the toast
+ dir: directionality of the toast (default: ltr)
+ hotkey: Keyboard shortcut that will move focus to the toaster area.
+ invert: Dark toasts in light mode and vice versa.
+ toast_options: These will act as default options for all toasts. See toast() for all available options.
+ gap: Gap between toasts when expanded
+ loading_icon: Changes the default loading icon
+ pause_when_page_is_hidden: Pauses toast timers when the page is hidden, e.g., when the tab is backgrounded, the browser is minimized, or the OS is locked.
+ style: The style of the component.
+ key: A unique key for the component.
+ id: The id for the component.
+ class_name: The class name for the component.
+ autofocus: Whether the component should take the focus once the page is loaded
+ custom_attrs: custom attribute
+ **props: The properties of the component.
Returns:
- The websocket target URL component.
+ The connection toaster component.
"""
...
-def default_connection_error() -> list[str | Var | Component]: ...
-
class ConnectionBanner(Component):
@overload
@classmethod
@@ -111,52 +149,22 @@ class ConnectionBanner(Component):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ConnectionBanner":
"""Create a connection banner component.
@@ -180,52 +188,22 @@ class ConnectionModal(Component):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ConnectionModal":
"""Create a connection banner component.
@@ -250,56 +228,27 @@ class WifiOffPulse(Icon):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "WifiOffPulse":
"""Create a wifi_off icon with an animated opacity pulse.
Args:
+ *children: The children of the component.
size: The size of the icon in pixels.
style: The style of the component.
key: A unique key for the component.
@@ -314,104 +263,60 @@ class WifiOffPulse(Icon):
"""
...
+ def add_imports(self) -> dict[str, str | ImportVar | list[str | ImportVar]]: ...
+
class ConnectionPulser(Div):
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ConnectionPulser":
"""Create a connection pulser component.
@@ -444,3 +349,8 @@ class ConnectionPulser(Div):
The connection pulser component.
"""
...
+
+connection_banner = ConnectionBanner.create
+connection_modal = ConnectionModal.create
+connection_toaster = ConnectionToaster.create
+connection_pulser = ConnectionPulser.create
diff --git a/reflex/components/core/breakpoints.py b/reflex/components/core/breakpoints.py
new file mode 100644
index 000000000..4b2372a70
--- /dev/null
+++ b/reflex/components/core/breakpoints.py
@@ -0,0 +1,95 @@
+"""Breakpoints utility."""
+
+from __future__ import annotations
+
+from typing import Dict, Tuple, TypeVar, Union
+
+breakpoints_values = ["30em", "48em", "62em", "80em", "96em"]
+breakpoint_names = ["xs", "sm", "md", "lg", "xl"]
+
+
+def set_breakpoints(values: Tuple[str, str, str, str, str]):
+ """Overwrite default breakpoint values.
+
+ Args:
+ values: CSS values in order defining the breakpoints of responsive layouts
+ """
+ breakpoints_values.clear()
+ breakpoints_values.extend(values)
+
+
+K = TypeVar("K")
+V = TypeVar("V")
+
+
+class Breakpoints(Dict[K, V]):
+ """A responsive styling helper."""
+
+ def factorize(self):
+ """Removes references to breakpoints names and instead replaces them with their corresponding values.
+
+ Returns:
+ The factorized breakpoints.
+ """
+ return Breakpoints(
+ {
+ (
+ breakpoints_values[breakpoint_names.index(k)]
+ if k in breakpoint_names
+ else ("0px" if k == "initial" else k)
+ ): v
+ for k, v in self.items()
+ if v is not None
+ }
+ )
+
+ @classmethod
+ def create(
+ cls,
+ custom: Dict[K, V] | None = None,
+ initial: V | None = None,
+ xs: V | None = None,
+ sm: V | None = None,
+ md: V | None = None,
+ lg: V | None = None,
+ xl: V | None = None,
+ ):
+ """Create a new instance of the helper. Only provide a custom component OR use named props.
+
+ Args:
+ custom: Custom mapping using CSS values or variables.
+ initial: Styling when in the inital width
+ xs: Styling when in the extra-small width
+ sm: Styling when in the small width
+ md: Styling when in the medium width
+ lg: Styling when in the large width
+ xl: Styling when in the extra-large width
+
+ Raises:
+ ValueError: If both custom and any other named parameters are provided.
+
+ Returns:
+ The responsive mapping.
+ """
+ thresholds = [initial, xs, sm, md, lg, xl]
+
+ if custom is not None:
+ if any((threshold is not None for threshold in thresholds)):
+ raise ValueError("Named props cannot be used with custom thresholds")
+
+ return Breakpoints(custom)
+ else:
+ return Breakpoints(
+ {
+ k: v
+ for k, v in zip(["initial", *breakpoint_names], thresholds)
+ if v is not None
+ }
+ )
+
+
+breakpoints = Breakpoints.create
+
+T = TypeVar("T")
+
+Responsive = Union[T, Breakpoints[str, T]]
diff --git a/reflex/components/core/client_side_routing.py b/reflex/components/core/client_side_routing.py
index 3d2090cd3..342c69632 100644
--- a/reflex/components/core/client_side_routing.py
+++ b/reflex/components/core/client_side_routing.py
@@ -7,29 +7,30 @@ setting a reactive state var "routeNotFound" to true if the redirect fails. The
`wait_for_client_redirect` function will render the component only after
routeNotFound becomes true.
"""
+
from __future__ import annotations
from reflex import constants
from reflex.components.component import Component
from reflex.components.core.cond import cond
-from reflex.vars import Var
+from reflex.vars.base import Var
-route_not_found: Var = Var.create_safe(constants.ROUTE_NOT_FOUND)
+route_not_found: Var = Var(_js_expr=constants.ROUTE_NOT_FOUND)
class ClientSideRouting(Component):
"""The client-side routing component."""
- library = "/utils/client_side_routing"
+ library = "$/utils/client_side_routing"
tag = "useClientSideRouting"
- def _get_hooks(self) -> str:
+ def add_hooks(self) -> list[str]:
"""Get the hooks to render.
Returns:
The useClientSideRouting hook.
"""
- return f"const {constants.ROUTE_NOT_FOUND} = {self.tag}()"
+ return [f"const {constants.ROUTE_NOT_FOUND} = {self.tag}()"]
def render(self) -> str:
"""Render the component.
diff --git a/reflex/components/core/client_side_routing.pyi b/reflex/components/core/client_side_routing.pyi
index 08fbf7e54..1d528daaf 100644
--- a/reflex/components/core/client_side_routing.pyi
+++ b/reflex/components/core/client_side_routing.pyi
@@ -1,20 +1,19 @@
"""Stub file for reflex/components/core/client_side_routing.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from reflex import constants
from reflex.components.component import Component
-from reflex.components.core.cond import cond
-from reflex.vars import Var
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
route_not_found: Var
class ClientSideRouting(Component):
+ def add_hooks(self) -> list[str]: ...
def render(self) -> str: ...
@overload
@classmethod
@@ -27,52 +26,22 @@ class ClientSideRouting(Component):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ClientSideRouting":
"""Create the component.
@@ -106,52 +75,22 @@ class Default404Page(Component):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Default404Page":
"""Create the component.
diff --git a/reflex/components/core/clipboard.py b/reflex/components/core/clipboard.py
new file mode 100644
index 000000000..cce0af4a7
--- /dev/null
+++ b/reflex/components/core/clipboard.py
@@ -0,0 +1,96 @@
+"""Global on_paste handling for Reflex app."""
+
+from __future__ import annotations
+
+from typing import Dict, List, Tuple, Union
+
+from reflex.components.base.fragment import Fragment
+from reflex.components.tags.tag import Tag
+from reflex.event import EventChain, EventHandler, identity_event
+from reflex.utils.format import format_prop, wrap
+from reflex.utils.imports import ImportVar
+from reflex.vars import get_unique_variable_name
+from reflex.vars.base import Var
+
+
+class Clipboard(Fragment):
+ """Clipboard component."""
+
+ # The element ids to attach the event listener to. Defaults to all child components or the document.
+ targets: Var[List[str]]
+
+ # Called when the user pastes data into the document. Data is a list of tuples of (mime_type, data). Binary types will be base64 encoded as a data uri.
+ on_paste: EventHandler[identity_event(List[Tuple[str, str]])]
+
+ # Save the original event actions for the on_paste event.
+ on_paste_event_actions: Var[Dict[str, Union[bool, int]]]
+
+ @classmethod
+ def create(cls, *children, **props):
+ """Create a Clipboard component.
+
+ Args:
+ *children: The children of the component.
+ **props: The properties of the component.
+
+ Returns:
+ The Clipboard Component.
+ """
+ if "targets" not in props:
+ # Add all children as targets if not specified.
+ targets = props.setdefault("targets", [])
+ for c in children:
+ if c.id is None:
+ c.id = f"clipboard_{get_unique_variable_name()}"
+ targets.append(c.id)
+
+ if "on_paste" in props:
+ # Capture the event actions for the on_paste handler if not specified.
+ props.setdefault("on_paste_event_actions", props["on_paste"].event_actions)
+
+ return super().create(*children, **props)
+
+ def _exclude_props(self) -> list[str]:
+ return super()._exclude_props() + ["on_paste", "on_paste_event_actions"]
+
+ def _render(self) -> Tag:
+ tag = super()._render()
+ tag.remove_props("targets")
+ # Ensure a different Fragment component is created whenever targets differ
+ tag.add_props(key=self.targets)
+ return tag
+
+ def add_imports(self) -> dict[str, ImportVar]:
+ """Add the imports for the Clipboard component.
+
+ Returns:
+ The import dict for the component.
+ """
+ return {
+ "$/utils/helpers/paste.js": ImportVar(
+ tag="usePasteHandler", is_default=True
+ ),
+ }
+
+ def add_hooks(self) -> list[str]:
+ """Add hook to register paste event listener.
+
+ Returns:
+ The hooks to add to the component.
+ """
+ on_paste = self.event_triggers["on_paste"]
+ if on_paste is None:
+ return []
+ if isinstance(on_paste, EventChain):
+ on_paste = wrap(str(format_prop(on_paste)).strip("{}"), "(")
+ return [
+ "usePasteHandler(%s, %s, %s)"
+ % (
+ str(self.targets),
+ str(self.on_paste_event_actions),
+ on_paste,
+ )
+ ]
+
+
+clipboard = Clipboard.create
diff --git a/reflex/components/core/clipboard.pyi b/reflex/components/core/clipboard.pyi
new file mode 100644
index 000000000..1284b8050
--- /dev/null
+++ b/reflex/components/core/clipboard.pyi
@@ -0,0 +1,71 @@
+"""Stub file for reflex/components/core/clipboard.py"""
+
+# ------------------- DO NOT EDIT ----------------------
+# This file was generated by `reflex/utils/pyi_generator.py`!
+# ------------------------------------------------------
+from typing import Any, Dict, List, Optional, Union, overload
+
+from reflex.components.base.fragment import Fragment
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.utils.imports import ImportVar
+from reflex.vars.base import Var
+
+class Clipboard(Fragment):
+ @overload
+ @classmethod
+ def create( # type: ignore
+ cls,
+ *children,
+ targets: Optional[Union[List[str], Var[List[str]]]] = None,
+ on_paste_event_actions: Optional[
+ Union[Dict[str, Union[bool, int]], Var[Dict[str, Union[bool, int]]]]
+ ] = None,
+ style: Optional[Style] = None,
+ key: Optional[Any] = None,
+ id: Optional[Any] = None,
+ class_name: Optional[Any] = None,
+ autofocus: Optional[bool] = None,
+ custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_paste: Optional[EventType[list[tuple[str, str]]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
+ ) -> "Clipboard":
+ """Create a Clipboard component.
+
+ Args:
+ *children: The children of the component.
+ targets: The element ids to attach the event listener to. Defaults to all child components or the document.
+ on_paste: Called when the user pastes data into the document. Data is a list of tuples of (mime_type, data). Binary types will be base64 encoded as a data uri.
+ on_paste_event_actions: Save the original event actions for the on_paste event.
+ style: The style of the component.
+ key: A unique key for the component.
+ id: The id for the component.
+ class_name: The class name for the component.
+ autofocus: Whether the component should take the focus once the page is loaded
+ custom_attrs: custom attribute
+ **props: The properties of the component.
+
+ Returns:
+ The Clipboard Component.
+ """
+ ...
+
+ def add_imports(self) -> dict[str, ImportVar]: ...
+ def add_hooks(self) -> list[str]: ...
+
+clipboard = Clipboard.create
diff --git a/reflex/components/core/cond.py b/reflex/components/core/cond.py
index 0e3e43672..e0c47f0fe 100644
--- a/reflex/components/core/cond.py
+++ b/reflex/components/core/cond.py
@@ -1,4 +1,5 @@
"""Create a list of components from an iterable."""
+
from __future__ import annotations
from typing import Any, Dict, Optional, overload
@@ -7,13 +8,14 @@ from reflex.components.base.fragment import Fragment
from reflex.components.component import BaseComponent, Component, MemoizationLeaf
from reflex.components.tags import CondTag, Tag
from reflex.constants import Dirs
-from reflex.constants.colors import Color
-from reflex.style import LIGHT_COLOR_MODE, color_mode
-from reflex.utils import format, imports
-from reflex.vars import BaseVar, Var, VarData
+from reflex.style import LIGHT_COLOR_MODE, resolved_color_mode
+from reflex.utils.imports import ImportDict, ImportVar
+from reflex.vars import VarData
+from reflex.vars.base import LiteralVar, Var
+from reflex.vars.number import ternary_operation
-_IS_TRUE_IMPORT = {
- f"/{Dirs.STATE_PATH}": {imports.ImportVar(tag="isTrue")},
+_IS_TRUE_IMPORT: ImportDict = {
+ f"$/{Dirs.STATE_PATH}": [ImportVar(tag="isTrue")],
}
@@ -92,33 +94,35 @@ class Cond(MemoizationLeaf):
).set(
props=tag.format_props(),
),
- cond_state=f"isTrue({self.cond._var_full_name})",
+ cond_state=f"isTrue({str(self.cond)})",
)
- def _get_imports(self) -> imports.ImportDict:
- return imports.merge_imports(
- super()._get_imports(),
- getattr(self.cond._var_data, "imports", {}),
- _IS_TRUE_IMPORT,
- )
+ def add_imports(self) -> ImportDict:
+ """Add imports for the Cond component.
+
+ Returns:
+ The import dict for the component.
+ """
+ var_data = VarData.merge(self.cond._get_all_var_data())
+
+ imports = var_data.old_school_imports() if var_data else {}
+
+ return {**imports, **_IS_TRUE_IMPORT}
@overload
-def cond(condition: Any, c1: Component, c2: Any) -> Component:
- ...
+def cond(condition: Any, c1: Component, c2: Any) -> Component: ...
@overload
-def cond(condition: Any, c1: Component) -> Component:
- ...
+def cond(condition: Any, c1: Component) -> Component: ...
@overload
-def cond(condition: Any, c1: Any, c2: Any) -> Var:
- ...
+def cond(condition: Any, c1: Any, c2: Any) -> Var: ...
-def cond(condition: Any, c1: Any, c2: Any = None):
+def cond(condition: Any, c1: Any, c2: Any = None) -> Component | Var:
"""Create a conditional component or Prop.
Args:
@@ -132,24 +136,16 @@ def cond(condition: Any, c1: Any, c2: Any = None):
Raises:
ValueError: If the arguments are invalid.
"""
- var_datas: list[VarData | None] = [
- VarData( # type: ignore
- imports=_IS_TRUE_IMPORT,
- ),
- ]
-
# Convert the condition to a Var.
- cond_var = Var.create(condition)
- assert cond_var is not None, "The condition must be set."
+ cond_var = LiteralVar.create(condition)
+ if cond_var is None:
+ raise ValueError("The condition must be set.")
# If the first component is a component, create a Cond component.
if isinstance(c1, BaseComponent):
- assert c2 is None or isinstance(
- c2, BaseComponent
- ), "Both arguments must be components."
+ if c2 is not None and not isinstance(c2, BaseComponent):
+ raise ValueError("Both arguments must be components.")
return Cond.create(cond_var, c1, c2)
- if isinstance(c1, Var):
- var_datas.append(c1._var_data)
# Otherwise, create a conditional Var.
# Check that the second argument is valid.
@@ -157,32 +153,21 @@ def cond(condition: Any, c1: Any, c2: Any = None):
raise ValueError("Both arguments must be props.")
if c2 is None:
raise ValueError("For conditional vars, the second argument must be set.")
- if isinstance(c2, Var):
- var_datas.append(c2._var_data)
def create_var(cond_part):
- return Var.create_safe(
- cond_part,
- _var_is_string=isinstance(cond_part, (str, Color)),
- )
+ return LiteralVar.create(cond_part)
# convert the truth and false cond parts into vars so the _var_data can be obtained.
c1 = create_var(c1)
c2 = create_var(c2)
- var_datas.extend([c1._var_data, c2._var_data])
# Create the conditional var.
- return cond_var._replace(
- _var_name=format.format_cond(
- cond=cond_var._var_full_name,
- true_value=c1,
- false_value=c2,
- is_prop=True,
- ),
- _var_type=c1._var_type if isinstance(c1, BaseVar) else type(c1),
- _var_is_local=False,
- _var_full_name_needs_state_prefix=False,
- merge_var_data=VarData.merge(*var_datas),
+ return ternary_operation(
+ cond_var.bool()._replace( # type: ignore
+ merge_var_data=VarData(imports=_IS_TRUE_IMPORT),
+ ), # type: ignore
+ c1,
+ c2,
)
@@ -197,7 +182,7 @@ def color_mode_cond(light: Any, dark: Any = None) -> Var | Component:
The conditional component or prop.
"""
return cond(
- color_mode == Var.create(LIGHT_COLOR_MODE, _var_is_string=True),
+ resolved_color_mode == LiteralVar.create(LIGHT_COLOR_MODE),
light,
dark,
)
diff --git a/reflex/components/core/debounce.py b/reflex/components/core/debounce.py
index 5fabd4486..86efb7dcd 100644
--- a/reflex/components/core/debounce.py
+++ b/reflex/components/core/debounce.py
@@ -6,7 +6,9 @@ from typing import Any, Type, Union
from reflex.components.component import Component
from reflex.constants import EventTriggers
-from reflex.vars import Var, VarData
+from reflex.event import EventHandler, empty_event
+from reflex.vars import VarData
+from reflex.vars.base import Var
DEFAULT_DEBOUNCE_TIMEOUT = 300
@@ -43,6 +45,9 @@ class DebounceInput(Component):
# The element to wrap
element: Var[Type[Component]]
+ # Fired when the input value changes
+ on_change: EventHandler[empty_event]
+
@classmethod
def create(cls, *children: Component, **props: Any) -> Component:
"""Create a DebounceInput component.
@@ -97,23 +102,23 @@ class DebounceInput(Component):
props.setdefault("style", {}).update(child.style)
if child.class_name is not None:
props["class_name"] = f"{props.get('class_name', '')} {child.class_name}"
+ for field in ("key", "special_props"):
+ if getattr(child, field) is not None:
+ props[field] = getattr(child, field)
child_ref = child.get_ref()
if props.get("input_ref") is None and child_ref:
- props["input_ref"] = Var.create_safe(child_ref, _var_is_local=False)
+ props["input_ref"] = Var(_js_expr=child_ref, _var_type=str)
props["id"] = child.id
# Set the child element to wrap, including any imports/hooks from the child.
props.setdefault(
"element",
- Var.create_safe(
- "{%s}" % (child.alias or child.tag),
- _var_is_local=False,
- _var_is_string=False,
- )._replace(
+ Var(
+ _js_expr=str(child.alias or child.tag),
_var_type=Type[Component],
- merge_var_data=VarData( # type: ignore
+ _var_data=VarData(
imports=child._get_imports(),
- hooks=child._get_hooks_internal(),
+ hooks=child._get_all_hooks(),
),
),
)
@@ -123,18 +128,14 @@ class DebounceInput(Component):
component.event_triggers.update(child.event_triggers)
component.children = child.children
component._rename_props = child._rename_props
+ outer_get_all_custom_code = component._get_all_custom_code
+ component._get_all_custom_code = lambda: outer_get_all_custom_code().union(
+ child._get_all_custom_code()
+ )
return component
- def get_event_triggers(self) -> dict[str, Any]:
- """Get the event triggers that pass the component's value to the handler.
-
- Returns:
- A dict mapping the event trigger to the var that is passed to the handler.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_CHANGE: lambda e0: [e0.value],
- }
-
def _render(self):
return super()._render().remove_props("ref")
+
+
+debounce_input = DebounceInput.create
diff --git a/reflex/components/core/debounce.pyi b/reflex/components/core/debounce.pyi
index 7b87a3cfe..6d7b76510 100644
--- a/reflex/components/core/debounce.pyi
+++ b/reflex/components/core/debounce.pyi
@@ -1,16 +1,14 @@
"""Stub file for reflex/components/core/debounce.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Type, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Any, Type, Union
from reflex.components.component import Component
-from reflex.constants import EventTriggers
-from reflex.vars import Var, VarData
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
DEFAULT_DEBOUNCE_TIMEOUT = 300
@@ -24,66 +22,32 @@ class DebounceInput(Component):
debounce_timeout: Optional[Union[Var[int], int]] = None,
force_notify_by_enter: Optional[Union[Var[bool], bool]] = None,
force_notify_on_blur: Optional[Union[Var[bool], bool]] = None,
- value: Optional[
- Union[Var[Union[str, int, float]], Union[str, int, float]]
- ] = None,
+ value: Optional[Union[Var[Union[float, int, str]], float, int, str]] = None,
input_ref: Optional[Union[Var[str], str]] = None,
- element: Optional[Union[Var[Type[Component]], Type[Component]]] = None,
+ element: Optional[Union[Type[Component], Var[Type[Component]]]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_change: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DebounceInput":
"""Create a DebounceInput component.
@@ -105,4 +69,5 @@ class DebounceInput(Component):
ValueError: if the child element does not have an on_change handler.
"""
...
- def get_event_triggers(self) -> dict[str, Any]: ...
+
+debounce_input = DebounceInput.create
diff --git a/reflex/components/core/foreach.py b/reflex/components/core/foreach.py
index 88f2886a8..a3f97d594 100644
--- a/reflex/components/core/foreach.py
+++ b/reflex/components/core/foreach.py
@@ -1,4 +1,5 @@
"""Create a list of components from an iterable."""
+
from __future__ import annotations
import inspect
@@ -8,8 +9,8 @@ from reflex.components.base.fragment import Fragment
from reflex.components.component import Component
from reflex.components.tags import IterTag
from reflex.constants import MemoizationMode
-from reflex.utils import console
-from reflex.vars import Var
+from reflex.state import ComponentState
+from reflex.vars.base import LiteralVar, Var
class ForeachVarError(TypeError):
@@ -36,35 +37,36 @@ class Foreach(Component):
cls,
iterable: Var[Iterable] | Iterable,
render_fn: Callable,
- **props,
) -> Foreach:
"""Create a foreach component.
Args:
iterable: The iterable to create components from.
render_fn: A function from the render args to the component.
- **props: The attributes to pass to each child component (deprecated).
Returns:
The foreach component.
Raises:
ForeachVarError: If the iterable is of type Any.
+ TypeError: If the render function is a ComponentState.
"""
- if props:
- console.deprecate(
- feature_name="Passing props to rx.foreach",
- reason="it does not have the intended effect and may be confusing",
- deprecation_version="0.5.0",
- removal_version="0.6.0",
- )
- iterable = Var.create_safe(iterable)
+ iterable = LiteralVar.create(iterable)
if iterable._var_type == Any:
raise ForeachVarError(
- f"Could not foreach over var `{iterable._var_full_name}` of type Any. "
+ f"Could not foreach over var `{str(iterable)}` of type Any. "
"(If you are trying to foreach over a state var, add a type annotation to the var). "
- "See https://reflex.dev/docs/library/layout/foreach/"
+ "See https://reflex.dev/docs/library/dynamic-rendering/foreach/"
)
+
+ if (
+ hasattr(render_fn, "__qualname__")
+ and render_fn.__qualname__ == ComponentState.create.__qualname__
+ ):
+ raise TypeError(
+ "Using a ComponentState as `render_fn` inside `rx.foreach` is not supported yet."
+ )
+
component = cls(
iterable=iterable,
render_fn=render_fn,
@@ -83,7 +85,8 @@ class Foreach(Component):
if len(params) == 0 or len(params) > 2:
raise ForeachRenderError(
"Expected 1 or 2 parameters in foreach render function, got "
- f"{[p.name for p in params]}. See https://reflex.dev/docs/library/layout/foreach/"
+ f"{[p.name for p in params]}. See "
+ "https://reflex.dev/docs/library/dynamic-rendering/foreach/"
)
if len(params) >= 1:
@@ -123,8 +126,11 @@ class Foreach(Component):
return dict(
tag,
- iterable_state=tag.iterable._var_full_name,
+ iterable_state=str(tag.iterable),
arg_name=tag.arg_var_name,
arg_index=tag.get_index_var_arg(),
iterable_type=tag.iterable._var_type.mro()[0].__name__,
)
+
+
+foreach = Foreach.create
diff --git a/reflex/components/core/html.py b/reflex/components/core/html.py
index e344cb3d7..cfe46e591 100644
--- a/reflex/components/core/html.py
+++ b/reflex/components/core/html.py
@@ -1,15 +1,16 @@
"""A html component."""
+
from typing import Dict
from reflex.components.el.elements.typography import Div
-from reflex.vars import Var
+from reflex.vars.base import Var
class Html(Div):
"""Render the html.
Returns:
- The code to render the html component.
+ The code to render the html component.
"""
# The HTML to render.
@@ -43,3 +44,6 @@ class Html(Div):
# Create the component.
return super().create(**props)
+
+
+html = Html.create
diff --git a/reflex/components/core/html.pyi b/reflex/components/core/html.pyi
index e07f455bb..7f3ff603d 100644
--- a/reflex/components/core/html.pyi
+++ b/reflex/components/core/html.pyi
@@ -1,15 +1,14 @@
"""Stub file for reflex/components/core/html.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Dict
from reflex.components.el.elements.typography import Div
-from reflex.vars import Var
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
class Html(Div):
@overload
@@ -18,100 +17,54 @@ class Html(Div):
cls,
*children,
dangerouslySetInnerHTML: Optional[
- Union[Var[Dict[str, str]], Dict[str, str]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Dict[str, str], Var[Dict[str, str]]]
] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Html":
"""Create a html component.
@@ -149,3 +102,5 @@ class Html(Div):
ValueError: If children are not provided or more than one child is provided.
"""
...
+
+html = Html.create
diff --git a/reflex/components/core/match.py b/reflex/components/core/match.py
index 97741b9fa..8b9382c89 100644
--- a/reflex/components/core/match.py
+++ b/reflex/components/core/match.py
@@ -5,12 +5,13 @@ from typing import Any, Dict, List, Optional, Tuple, Union
from reflex.components.base import Fragment
from reflex.components.component import BaseComponent, Component, MemoizationLeaf
-from reflex.components.core.colors import Color
from reflex.components.tags import MatchTag, Tag
from reflex.style import Style
-from reflex.utils import format, imports, types
+from reflex.utils import format, types
from reflex.utils.exceptions import MatchTypeError
-from reflex.vars import BaseVar, Var, VarData
+from reflex.utils.imports import ImportDict
+from reflex.vars import VarData
+from reflex.vars.base import LiteralVar, Var
class Match(MemoizationLeaf):
@@ -26,7 +27,7 @@ class Match(MemoizationLeaf):
default: Any
@classmethod
- def create(cls, cond: Any, *cases) -> Union[Component, BaseVar]:
+ def create(cls, cond: Any, *cases) -> Union[Component, Var]:
"""Create a Match Component.
Args:
@@ -45,7 +46,7 @@ class Match(MemoizationLeaf):
cls._validate_return_types(match_cases)
- if default is None and types._issubclass(type(match_cases[0][-1]), BaseVar):
+ if default is None and types._issubclass(type(match_cases[0][-1]), Var):
raise ValueError(
"For cases with return types as Vars, a default case must be provided"
)
@@ -55,7 +56,7 @@ class Match(MemoizationLeaf):
)
@classmethod
- def _create_condition_var(cls, cond: Any) -> BaseVar:
+ def _create_condition_var(cls, cond: Any) -> Var:
"""Convert the condition to a Var.
Args:
@@ -67,16 +68,16 @@ class Match(MemoizationLeaf):
Raises:
ValueError: If the condition is not provided.
"""
- match_cond_var = Var.create(cond, _var_is_string=isinstance(cond, str))
+ match_cond_var = LiteralVar.create(cond)
if match_cond_var is None:
raise ValueError("The condition must be set")
- return match_cond_var # type: ignore
+ return match_cond_var
@classmethod
def _process_cases(
cls, cases: List
- ) -> Tuple[List, Optional[Union[BaseVar, BaseComponent]]]:
+ ) -> Tuple[List, Optional[Union[Var, BaseComponent]]]:
"""Process the list of match cases and the catchall default case.
Args:
@@ -93,6 +94,9 @@ class Match(MemoizationLeaf):
if len([case for case in cases if not isinstance(case, tuple)]) > 1:
raise ValueError("rx.match can only have one default case.")
+ if not cases:
+ raise ValueError("rx.match should have at least one case.")
+
# Get the default case which should be the last non-tuple arg
if not isinstance(cases[-1], tuple):
default = cases.pop()
@@ -102,7 +106,7 @@ class Match(MemoizationLeaf):
else default
)
- return cases, default # type: ignore
+ return cases, default
@classmethod
def _create_case_var_with_var_data(cls, case_element):
@@ -116,17 +120,12 @@ class Match(MemoizationLeaf):
Returns:
The case element Var.
"""
- _var_data = case_element._var_data if isinstance(case_element, Style) else None # type: ignore
- case_element = Var.create(
- case_element,
- _var_is_string=isinstance(case_element, (str, Color)),
- )
- if _var_data is not None:
- case_element._var_data = VarData.merge(case_element._var_data, _var_data) # type: ignore
+ _var_data = case_element._var_data if isinstance(case_element, Style) else None
+ case_element = LiteralVar.create(case_element, _var_data=_var_data)
return case_element
@classmethod
- def _process_match_cases(cls, cases: List) -> List[List[BaseVar]]:
+ def _process_match_cases(cls, cases: List) -> List[List[Var]]:
"""Process the individual match cases.
Args:
@@ -158,7 +157,7 @@ class Match(MemoizationLeaf):
if not isinstance(element, BaseComponent)
else element
)
- if not isinstance(el, (BaseVar, BaseComponent)):
+ if not isinstance(el, (Var, BaseComponent)):
raise ValueError("Case element must be a var or component")
case_list.append(el)
@@ -167,7 +166,7 @@ class Match(MemoizationLeaf):
return match_cases
@classmethod
- def _validate_return_types(cls, match_cases: List[List[BaseVar]]) -> None:
+ def _validate_return_types(cls, match_cases: List[List[Var]]) -> None:
"""Validate that match cases have the same return types.
Args:
@@ -181,14 +180,14 @@ class Match(MemoizationLeaf):
if types._isinstance(first_case_return, BaseComponent):
return_type = BaseComponent
- elif types._isinstance(first_case_return, BaseVar):
- return_type = BaseVar
+ elif types._isinstance(first_case_return, Var):
+ return_type = Var
for index, case in enumerate(match_cases):
if not types._issubclass(type(case[-1]), return_type):
raise MatchTypeError(
f"Match cases should have the same return types. Case {index} with return "
- f"value `{case[-1]._var_name if isinstance(case[-1], BaseVar) else textwrap.shorten(str(case[-1]), width=250)}`"
+ f"value `{case[-1]._js_expr if isinstance(case[-1], Var) else textwrap.shorten(str(case[-1]), width=250)}`"
f" of type {type(case[-1])!r} is not {return_type}"
)
@@ -196,9 +195,9 @@ class Match(MemoizationLeaf):
def _create_match_cond_var_or_component(
cls,
match_cond_var: Var,
- match_cases: List[List[BaseVar]],
- default: Optional[Union[BaseVar, BaseComponent]],
- ) -> Union[Component, BaseVar]:
+ match_cases: List[List[Var]],
+ default: Optional[Union[Var, BaseComponent]],
+ ) -> Union[Component, Var]:
"""Create and return the match condition var or component.
Args:
@@ -229,28 +228,22 @@ class Match(MemoizationLeaf):
# Validate the match cases (as well as the default case) to have Var return types.
if any(
- case for case in match_cases if not types._isinstance(case[-1], BaseVar)
- ) or not types._isinstance(default, BaseVar):
+ case for case in match_cases if not types._isinstance(case[-1], Var)
+ ) or not types._isinstance(default, Var):
raise ValueError("Return types of match cases should be Vars.")
- # match cases and default should all be Vars at this point.
- # Retrieve var data of every var in the match cases and default.
- var_data = [
- *[el._var_data for case in match_cases for el in case],
- default._var_data, # type: ignore
- ]
-
- return match_cond_var._replace(
- _var_name=format.format_match(
- cond=match_cond_var._var_name_unwrapped,
- match_cases=match_cases, # type: ignore
+ return Var(
+ _js_expr=format.format_match(
+ cond=str(match_cond_var),
+ match_cases=match_cases,
default=default, # type: ignore
),
_var_type=default._var_type, # type: ignore
- _var_is_local=False,
- _var_full_name_needs_state_prefix=False,
- _var_is_string=False,
- merge_var_data=VarData.merge(*var_data),
+ _var_data=VarData.merge(
+ match_cond_var._get_all_var_data(),
+ *[el._get_all_var_data() for case in match_cases for el in case],
+ default._get_all_var_data(), # type: ignore
+ ),
)
def _render(self) -> Tag:
@@ -268,8 +261,14 @@ class Match(MemoizationLeaf):
tag.name = "match"
return dict(tag)
- def _get_imports(self) -> imports.ImportDict:
- return imports.merge_imports(
- super()._get_imports(),
- getattr(self.cond._var_data, "imports", {}),
- )
+ def add_imports(self) -> ImportDict:
+ """Add imports for the Match component.
+
+ Returns:
+ The import dict.
+ """
+ var_data = VarData.merge(self.cond._get_all_var_data())
+ return var_data.old_school_imports() if var_data else {}
+
+
+match = Match.create
diff --git a/reflex/components/core/responsive.py b/reflex/components/core/responsive.py
index 98033fd70..e1c7f0cb3 100644
--- a/reflex/components/core/responsive.py
+++ b/reflex/components/core/responsive.py
@@ -1,6 +1,6 @@
"""Responsive components."""
-from reflex.components.radix.themes.layout import Box
+from reflex.components.radix.themes.layout.box import Box
# Add responsive styles shortcuts.
diff --git a/reflex/components/core/upload.py b/reflex/components/core/upload.py
index b3ac37c15..787cca9d0 100644
--- a/reflex/components/core/upload.py
+++ b/reflex/components/core/upload.py
@@ -2,34 +2,41 @@
from __future__ import annotations
-import os
from pathlib import Path
-from typing import Any, Callable, ClassVar, Dict, List, Optional, Union
+from typing import Any, Callable, ClassVar, Dict, List, Optional, Tuple
-from reflex import constants
-from reflex.components.chakra.forms.input import Input
-from reflex.components.chakra.layout.box import Box
-from reflex.components.component import Component, ComponentNamespace, MemoizationLeaf
+from reflex.components.component import (
+ Component,
+ ComponentNamespace,
+ MemoizationLeaf,
+ StatefulComponent,
+)
+from reflex.components.el.elements.forms import Input
+from reflex.components.radix.themes.layout.box import Box
+from reflex.config import environment
from reflex.constants import Dirs
+from reflex.constants.compiler import Imports
from reflex.event import (
CallableEventSpec,
EventChain,
+ EventHandler,
EventSpec,
call_event_fn,
call_script,
parse_args_spec,
)
-from reflex.utils import imports
-from reflex.vars import BaseVar, CallableVar, Var, VarData
+from reflex.utils import format
+from reflex.utils.imports import ImportVar
+from reflex.vars import VarData
+from reflex.vars.base import CallableVar, LiteralVar, Var, get_unique_variable_name
+from reflex.vars.sequence import LiteralStringVar
DEFAULT_UPLOAD_ID: str = "default"
-upload_files_context_var_data: VarData = VarData( # type: ignore
+upload_files_context_var_data: VarData = VarData(
imports={
- "react": {imports.ImportVar(tag="useContext")},
- f"/{Dirs.CONTEXTS_PATH}": {
- imports.ImportVar(tag="UploadFilesContext"),
- },
+ "react": "useContext",
+ f"$/{Dirs.CONTEXTS_PATH}": "UploadFilesContext",
},
hooks={
"const [filesById, setFilesById] = useContext(UploadFilesContext);": None,
@@ -38,7 +45,7 @@ upload_files_context_var_data: VarData = VarData( # type: ignore
@CallableVar
-def upload_file(id_: str = DEFAULT_UPLOAD_ID) -> BaseVar:
+def upload_file(id_: str = DEFAULT_UPLOAD_ID) -> Var:
"""Get the file upload drop trigger.
This var is passed to the dropzone component to update the file list when a
@@ -50,15 +57,25 @@ def upload_file(id_: str = DEFAULT_UPLOAD_ID) -> BaseVar:
Returns:
A var referencing the file upload drop trigger.
"""
- return BaseVar(
- _var_name=f"e => setFilesById(filesById => ({{...filesById, {id_}: e}}))",
+ id_var = LiteralStringVar.create(id_)
+ var_name = f"""e => setFilesById(filesById => {{
+ const updatedFilesById = Object.assign({{}}, filesById);
+ updatedFilesById[{str(id_var)}] = e;
+ return updatedFilesById;
+ }})
+ """
+
+ return Var(
+ _js_expr=var_name,
_var_type=EventChain,
- _var_data=upload_files_context_var_data,
+ _var_data=VarData.merge(
+ upload_files_context_var_data, id_var._get_all_var_data()
+ ),
)
@CallableVar
-def selected_files(id_: str = DEFAULT_UPLOAD_ID) -> BaseVar:
+def selected_files(id_: str = DEFAULT_UPLOAD_ID) -> Var:
"""Get the list of selected files.
Args:
@@ -67,11 +84,14 @@ def selected_files(id_: str = DEFAULT_UPLOAD_ID) -> BaseVar:
Returns:
A var referencing the list of selected file paths.
"""
- return BaseVar(
- _var_name=f"(filesById.{id_} ? filesById.{id_}.map((f) => (f.path || f.name)) : [])",
+ id_var = LiteralStringVar.create(id_)
+ return Var(
+ _js_expr=f"(filesById[{str(id_var)}] ? filesById[{str(id_var)}].map((f) => (f.path || f.name)) : [])",
_var_type=List[str],
- _var_data=upload_files_context_var_data,
- )
+ _var_data=VarData.merge(
+ upload_files_context_var_data, id_var._get_all_var_data()
+ ),
+ ).guess_type()
@CallableEventSpec
@@ -99,7 +119,9 @@ def cancel_upload(upload_id: str) -> EventSpec:
Returns:
An event spec that cancels the upload when triggered.
"""
- return call_script(f"upload_controllers[{upload_id!r}]?.abort()")
+ return call_script(
+ f"upload_controllers[{str(LiteralVar.create(upload_id))}]?.abort()"
+ )
def get_upload_dir() -> Path:
@@ -110,23 +132,20 @@ def get_upload_dir() -> Path:
"""
Upload.is_used = True
- uploaded_files_dir = Path(
- os.environ.get("REFLEX_UPLOADED_FILES_DIR", "./uploaded_files")
- )
+ uploaded_files_dir = environment.REFLEX_UPLOADED_FILES_DIR
uploaded_files_dir.mkdir(parents=True, exist_ok=True)
return uploaded_files_dir
-uploaded_files_url_prefix: Var = Var.create_safe(
- "${getBackendURL(env.UPLOAD)}"
-)._replace(
- merge_var_data=VarData( # type: ignore
+uploaded_files_url_prefix = Var(
+ _js_expr="getBackendURL(env.UPLOAD)",
+ _var_data=VarData(
imports={
- f"/{Dirs.STATE_PATH}": {imports.ImportVar(tag="getBackendURL")},
- "/env.json": {imports.ImportVar(tag="env", is_default=True)},
+ f"$/{Dirs.STATE_PATH}": "getBackendURL",
+ "$/env.json": ImportVar(tag="env", is_default=True),
}
- )
-)
+ ),
+).to(str)
def get_upload_url(file_path: str) -> Var[str]:
@@ -140,12 +159,10 @@ def get_upload_url(file_path: str) -> Var[str]:
"""
Upload.is_used = True
- return Var.create_safe(
- f"{uploaded_files_url_prefix}/{file_path}", _var_is_string=True
- )
+ return uploaded_files_url_prefix + "/" + file_path
-def _on_drop_spec(files: Var):
+def _on_drop_spec(files: Var) -> Tuple[Var[Any]]:
"""Args spec for the on_drop event trigger.
Args:
@@ -154,24 +171,22 @@ def _on_drop_spec(files: Var):
Returns:
Signature for on_drop handler including the files to upload.
"""
- return [files]
+ return (files,)
class UploadFilesProvider(Component):
"""AppWrap component that provides a dict of selected files by ID via useContext."""
- library = f"/{Dirs.CONTEXTS_PATH}"
+ library = f"$/{Dirs.CONTEXTS_PATH}"
tag = "UploadFilesProvider"
class Upload(MemoizationLeaf):
"""A file upload component."""
- library = "react-dropzone@14.2.3"
+ library = "react-dropzone@14.2.10"
- tag = "ReactDropzone"
-
- is_default = True
+ tag = ""
# The list of accepted file types. This should be a dictionary of MIME types as keys and array of file formats as
# values.
@@ -191,7 +206,7 @@ class Upload(MemoizationLeaf):
min_size: Var[int]
# Whether to allow multiple files to be uploaded.
- multiple: Var[bool] = True # type: ignore
+ multiple: Var[bool]
# Whether to disable click to upload.
no_click: Var[bool]
@@ -205,6 +220,9 @@ class Upload(MemoizationLeaf):
# Marked True when any Upload component is created.
is_used: ClassVar[bool] = False
+ # Fired when files are dropped.
+ on_drop: EventHandler[_on_drop_spec]
+
@classmethod
def create(cls, *children, **props) -> Component:
"""Create an upload component.
@@ -219,6 +237,8 @@ class Upload(MemoizationLeaf):
# Mark the Upload component as used in the app.
cls.is_used = True
+ props.setdefault("multiple", True)
+
# Apply the default classname
given_class_name = props.pop("class_name", [])
if isinstance(given_class_name, str):
@@ -230,19 +250,6 @@ class Upload(MemoizationLeaf):
upload_props = {
key: value for key, value in props.items() if key in supported_props
}
- # The file input to use.
- upload = Input.create(type_="file")
- upload.special_props = {
- BaseVar(_var_name="{...getInputProps()}", _var_type=None)
- }
-
- # The dropzone to use.
- zone = Box.create(
- upload,
- *children,
- **{k: v for k, v in props.items() if k not in supported_props},
- )
- zone.special_props = {BaseVar(_var_name="{...getRootProps()}", _var_type=None)}
# Create the component.
upload_props["id"] = props.get("id", DEFAULT_UPLOAD_ID)
@@ -264,21 +271,75 @@ class Upload(MemoizationLeaf):
),
)
upload_props["on_drop"] = on_drop
- return super().create(
- zone,
+
+ input_props_unique_name = get_unique_variable_name()
+ root_props_unique_name = get_unique_variable_name()
+
+ event_var, callback_str = StatefulComponent._get_memoized_event_triggers(
+ Box.create(on_click=upload_props["on_drop"]) # type: ignore
+ )["on_click"]
+
+ upload_props["on_drop"] = event_var
+
+ upload_props = {
+ format.to_camel_case(key): value for key, value in upload_props.items()
+ }
+
+ use_dropzone_arguements = {
+ "onDrop": event_var,
**upload_props,
+ }
+
+ left_side = f"const {{getRootProps: {root_props_unique_name}, getInputProps: {input_props_unique_name}}} "
+ right_side = f"useDropzone({str(Var.create(use_dropzone_arguements))})"
+
+ var_data = VarData.merge(
+ VarData(
+ imports=Imports.EVENTS,
+ hooks={
+ "const [addEvents, connectError] = useContext(EventLoopContext);": None
+ },
+ ),
+ event_var._get_all_var_data(),
+ VarData(
+ hooks={
+ callback_str: None,
+ f"{left_side} = {right_side};": None,
+ },
+ imports={
+ "react-dropzone": "useDropzone",
+ **Imports.EVENTS,
+ },
+ ),
)
- def get_event_triggers(self) -> dict[str, Union[Var, Any]]:
- """Get the event triggers that pass the component's value to the handler.
+ # The file input to use.
+ upload = Input.create(type="file")
+ upload.special_props = [
+ Var(
+ _js_expr=f"{{...{input_props_unique_name}()}}",
+ _var_type=None,
+ _var_data=var_data,
+ )
+ ]
- Returns:
- A dict mapping the event trigger to the var that is passed to the handler.
- """
- return {
- **super().get_event_triggers(),
- constants.EventTriggers.ON_DROP: _on_drop_spec,
- }
+ # The dropzone to use.
+ zone = Box.create(
+ upload,
+ *children,
+ **{k: v for k, v in props.items() if k not in supported_props},
+ )
+ zone.special_props = [
+ Var(
+ _js_expr=f"{{...{root_props_unique_name}()}}",
+ _var_type=None,
+ _var_data=var_data,
+ )
+ ]
+
+ return super().create(
+ zone,
+ )
@classmethod
def _update_arg_tuple_for_on_drop(cls, arg_value: tuple[Var, Var]):
@@ -290,16 +351,11 @@ class Upload(MemoizationLeaf):
Returns:
The updated arg_value tuple when arg is "files", otherwise the original arg_value.
"""
- if arg_value[0]._var_name == "files":
+ if arg_value[0]._js_expr == "files":
placeholder = parse_args_spec(_on_drop_spec)[0]
return (arg_value[0], placeholder)
return arg_value
- def _render(self):
- out = super()._render()
- out.args = ("getRootProps", "getInputProps")
- return out
-
@staticmethod
def _get_app_wrap_components() -> dict[tuple[int, str], Component]:
return {
@@ -340,3 +396,6 @@ class UploadNamespace(ComponentNamespace):
root = Upload.create
__call__ = StyledUpload.create
+
+
+upload = UploadNamespace()
diff --git a/reflex/components/core/upload.pyi b/reflex/components/core/upload.pyi
index e415761e0..a63854ef2 100644
--- a/reflex/components/core/upload.pyi
+++ b/reflex/components/core/upload.pyi
@@ -1,44 +1,48 @@
"""Stub file for reflex/components/core/upload.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-import os
from pathlib import Path
-from typing import Any, Callable, ClassVar, Dict, List, Optional, Union
-from reflex import constants
-from reflex.components.chakra.forms.input import Input
-from reflex.components.chakra.layout.box import Box
-from reflex.components.component import Component, ComponentNamespace, MemoizationLeaf
+from typing import Any, ClassVar, Dict, List, Optional, Union, overload
+
+from reflex.components.component import (
+ Component,
+ ComponentNamespace,
+ MemoizationLeaf,
+)
from reflex.constants import Dirs
from reflex.event import (
CallableEventSpec,
- EventChain,
EventSpec,
- call_event_fn,
- call_script,
- parse_args_spec,
+ EventType,
)
-from reflex.utils import imports
-from reflex.vars import BaseVar, CallableVar, Var, VarData
+from reflex.style import Style
+from reflex.utils.imports import ImportVar
+from reflex.vars import VarData
+from reflex.vars.base import CallableVar, Var
DEFAULT_UPLOAD_ID: str
upload_files_context_var_data: VarData
@CallableVar
-def upload_file(id_: str = DEFAULT_UPLOAD_ID) -> BaseVar: ...
+def upload_file(id_: str = DEFAULT_UPLOAD_ID) -> Var: ...
@CallableVar
-def selected_files(id_: str = DEFAULT_UPLOAD_ID) -> BaseVar: ...
+def selected_files(id_: str = DEFAULT_UPLOAD_ID) -> Var: ...
@CallableEventSpec
def clear_selected_files(id_: str = DEFAULT_UPLOAD_ID) -> EventSpec: ...
def cancel_upload(upload_id: str) -> EventSpec: ...
def get_upload_dir() -> Path: ...
-uploaded_files_url_prefix: Var
+uploaded_files_url_prefix = Var(
+ _js_expr="getBackendURL(env.UPLOAD)",
+ _var_data=VarData(
+ imports={
+ f"$/{Dirs.STATE_PATH}": "getBackendURL",
+ "$/env.json": ImportVar(tag="env", is_default=True),
+ }
+ ),
+).to(str)
def get_upload_url(file_path: str) -> Var[str]: ...
@@ -54,52 +58,22 @@ class UploadFilesProvider(Component):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "UploadFilesProvider":
"""Create the component.
@@ -126,9 +100,7 @@ class Upload(MemoizationLeaf):
def create( # type: ignore
cls,
*children,
- accept: Optional[
- Union[Var[Optional[Dict[str, List]]], Optional[Dict[str, List]]]
- ] = None,
+ accept: Optional[Union[Dict[str, List], Var[Optional[Dict[str, List]]]]] = None,
disabled: Optional[Union[Var[bool], bool]] = None,
max_files: Optional[Union[Var[int], int]] = None,
max_size: Optional[Union[Var[int], int]] = None,
@@ -143,55 +115,23 @@ class Upload(MemoizationLeaf):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_drop: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_drop: Optional[EventType[Any]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Upload":
"""Create an upload component.
@@ -206,6 +146,7 @@ class Upload(MemoizationLeaf):
no_click: Whether to disable click to upload.
no_drag: Whether to disable drag and drop.
no_keyboard: Whether to disable using the space/enter keys to upload.
+ on_drop: Fired when files are dropped.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -218,7 +159,6 @@ class Upload(MemoizationLeaf):
The upload component.
"""
...
- def get_event_triggers(self) -> dict[str, Union[Var, Any]]: ...
class StyledUpload(Upload):
@overload
@@ -226,9 +166,7 @@ class StyledUpload(Upload):
def create( # type: ignore
cls,
*children,
- accept: Optional[
- Union[Var[Optional[Dict[str, List]]], Optional[Dict[str, List]]]
- ] = None,
+ accept: Optional[Union[Dict[str, List], Var[Optional[Dict[str, List]]]]] = None,
disabled: Optional[Union[Var[bool], bool]] = None,
max_files: Optional[Union[Var[int], int]] = None,
max_size: Optional[Union[Var[int], int]] = None,
@@ -243,55 +181,23 @@ class StyledUpload(Upload):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_drop: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_drop: Optional[EventType[Any]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "StyledUpload":
"""Create the styled upload component.
@@ -306,6 +212,7 @@ class StyledUpload(Upload):
no_click: Whether to disable click to upload.
no_drag: Whether to disable drag and drop.
no_keyboard: Whether to disable using the space/enter keys to upload.
+ on_drop: Fired when files are dropped.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -325,9 +232,7 @@ class UploadNamespace(ComponentNamespace):
@staticmethod
def __call__(
*children,
- accept: Optional[
- Union[Var[Optional[Dict[str, List]]], Optional[Dict[str, List]]]
- ] = None,
+ accept: Optional[Union[Dict[str, List], Var[Optional[Dict[str, List]]]]] = None,
disabled: Optional[Union[Var[bool], bool]] = None,
max_files: Optional[Union[Var[int], int]] = None,
max_size: Optional[Union[Var[int], int]] = None,
@@ -342,55 +247,23 @@ class UploadNamespace(ComponentNamespace):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_drop: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_drop: Optional[EventType[Any]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "StyledUpload":
"""Create the styled upload component.
@@ -405,6 +278,7 @@ class UploadNamespace(ComponentNamespace):
no_click: Whether to disable click to upload.
no_drag: Whether to disable drag and drop.
no_keyboard: Whether to disable using the space/enter keys to upload.
+ on_drop: Fired when files are dropped.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -417,3 +291,5 @@ class UploadNamespace(ComponentNamespace):
The styled upload component.
"""
...
+
+upload = UploadNamespace()
diff --git a/reflex/components/datadisplay/__init__.py b/reflex/components/datadisplay/__init__.py
index 2d90b1843..1aff69676 100644
--- a/reflex/components/datadisplay/__init__.py
+++ b/reflex/components/datadisplay/__init__.py
@@ -1,11 +1,20 @@
"""Data grid components."""
-from .code import CodeBlock
-from .code import LiteralCodeBlockTheme as LiteralCodeBlockTheme
-from .code import LiteralCodeLanguage as LiteralCodeLanguage
-from .dataeditor import DataEditor, DataEditorTheme
-from .logo import logo
+from __future__ import annotations
-code_block = CodeBlock.create
-data_editor = DataEditor.create
-data_editor_theme = DataEditorTheme
+from reflex.utils import lazy_loader
+
+_SUBMOD_ATTRS: dict[str, list[str]] = {
+ "code": [
+ "CodeBlock",
+ "code_block",
+ "LiteralCodeLanguage",
+ ],
+ "dataeditor": ["data_editor", "data_editor_theme", "DataEditorTheme"],
+ "logo": ["logo"],
+}
+
+__getattr__, __dir__, __all__ = lazy_loader.attach(
+ __name__,
+ submod_attrs=_SUBMOD_ATTRS,
+)
diff --git a/reflex/components/datadisplay/__init__.pyi b/reflex/components/datadisplay/__init__.pyi
new file mode 100644
index 000000000..32b29d106
--- /dev/null
+++ b/reflex/components/datadisplay/__init__.pyi
@@ -0,0 +1,12 @@
+"""Stub file for reflex/components/datadisplay/__init__.py"""
+# ------------------- DO NOT EDIT ----------------------
+# This file was generated by `reflex/utils/pyi_generator.py`!
+# ------------------------------------------------------
+
+from .code import CodeBlock as CodeBlock
+from .code import LiteralCodeLanguage as LiteralCodeLanguage
+from .code import code_block as code_block
+from .dataeditor import DataEditorTheme as DataEditorTheme
+from .dataeditor import data_editor as data_editor
+from .dataeditor import data_editor_theme as data_editor_theme
+from .logo import logo as logo
diff --git a/reflex/components/datadisplay/code.py b/reflex/components/datadisplay/code.py
index c59256b07..53761284a 100644
--- a/reflex/components/datadisplay/code.py
+++ b/reflex/components/datadisplay/code.py
@@ -1,69 +1,21 @@
"""A code component."""
+
from __future__ import annotations
-import re
-from typing import Dict, Literal, Optional, Union
+import dataclasses
+from typing import ClassVar, Dict, Literal, Optional, Union
-from reflex.components.chakra.forms import Button
-from reflex.components.chakra.layout import Box
-from reflex.components.chakra.media import Icon
-from reflex.components.component import Component
+from reflex.components.component import Component, ComponentNamespace
from reflex.components.core.cond import color_mode_cond
+from reflex.components.lucide.icon import Icon
+from reflex.components.radix.themes.components.button import Button
+from reflex.components.radix.themes.layout.box import Box
from reflex.constants.colors import Color
from reflex.event import set_clipboard
from reflex.style import Style
-from reflex.utils import format, imports
-from reflex.utils.imports import ImportVar
-from reflex.vars import Var
-
-LiteralCodeBlockTheme = Literal[
- "a11y-dark",
- "atom-dark",
- "cb",
- "coldark-cold",
- "coldark-dark",
- "coy",
- "coy-without-shadows",
- "darcula",
- "dark",
- "dracula",
- "duotone-dark",
- "duotone-earth",
- "duotone-forest",
- "duotone-light",
- "duotone-sea",
- "duotone-space",
- "funky",
- "ghcolors",
- "gruvbox-dark",
- "gruvbox-light",
- "holi-theme",
- "hopscotch",
- "light", # not present in react-syntax-highlighter styles
- "lucario",
- "material-dark",
- "material-light",
- "material-oceanic",
- "night-owl",
- "nord",
- "okaidia",
- "one-dark",
- "one-light",
- "pojoaque",
- "prism",
- "shades-of-purple",
- "solarized-dark-atom",
- "solarizedlight",
- "synthwave84",
- "tomorrow",
- "twilight",
- "vs",
- "vs-dark",
- "vsc-dark-plus",
- "xonokai",
- "z-touch",
-]
-
+from reflex.utils import console, format
+from reflex.utils.imports import ImportDict, ImportVar
+from reflex.vars.base import LiteralVar, Var, VarData
LiteralCodeLanguage = Literal[
"abap",
@@ -348,20 +300,98 @@ LiteralCodeLanguage = Literal[
]
+def construct_theme_var(theme: str) -> Var[Theme]:
+ """Construct a theme var.
+
+ Args:
+ theme: The theme to construct.
+
+ Returns:
+ The constructed theme var.
+ """
+ return Var(
+ theme,
+ _var_data=VarData(
+ imports={
+ f"react-syntax-highlighter/dist/cjs/styles/prism/{format.to_kebab_case(theme)}": [
+ ImportVar(tag=theme, is_default=True, install=False)
+ ]
+ }
+ ),
+ )
+
+
+@dataclasses.dataclass(init=False)
+class Theme:
+ """Themes for the CodeBlock component."""
+
+ a11y_dark: ClassVar[Var[Theme]] = construct_theme_var("a11yDark")
+ atom_dark: ClassVar[Var[Theme]] = construct_theme_var("atomDark")
+ cb: ClassVar[Var[Theme]] = construct_theme_var("cb")
+ coldark_cold: ClassVar[Var[Theme]] = construct_theme_var("coldarkCold")
+ coldark_dark: ClassVar[Var[Theme]] = construct_theme_var("coldarkDark")
+ coy: ClassVar[Var[Theme]] = construct_theme_var("coy")
+ coy_without_shadows: ClassVar[Var[Theme]] = construct_theme_var("coyWithoutShadows")
+ darcula: ClassVar[Var[Theme]] = construct_theme_var("darcula")
+ dark: ClassVar[Var[Theme]] = construct_theme_var("oneDark")
+ dracula: ClassVar[Var[Theme]] = construct_theme_var("dracula")
+ duotone_dark: ClassVar[Var[Theme]] = construct_theme_var("duotoneDark")
+ duotone_earth: ClassVar[Var[Theme]] = construct_theme_var("duotoneEarth")
+ duotone_forest: ClassVar[Var[Theme]] = construct_theme_var("duotoneForest")
+ duotone_light: ClassVar[Var[Theme]] = construct_theme_var("duotoneLight")
+ duotone_sea: ClassVar[Var[Theme]] = construct_theme_var("duotoneSea")
+ duotone_space: ClassVar[Var[Theme]] = construct_theme_var("duotoneSpace")
+ funky: ClassVar[Var[Theme]] = construct_theme_var("funky")
+ ghcolors: ClassVar[Var[Theme]] = construct_theme_var("ghcolors")
+ gruvbox_dark: ClassVar[Var[Theme]] = construct_theme_var("gruvboxDark")
+ gruvbox_light: ClassVar[Var[Theme]] = construct_theme_var("gruvboxLight")
+ holi_theme: ClassVar[Var[Theme]] = construct_theme_var("holiTheme")
+ hopscotch: ClassVar[Var[Theme]] = construct_theme_var("hopscotch")
+ light: ClassVar[Var[Theme]] = construct_theme_var("oneLight")
+ lucario: ClassVar[Var[Theme]] = construct_theme_var("lucario")
+ material_dark: ClassVar[Var[Theme]] = construct_theme_var("materialDark")
+ material_light: ClassVar[Var[Theme]] = construct_theme_var("materialLight")
+ material_oceanic: ClassVar[Var[Theme]] = construct_theme_var("materialOceanic")
+ night_owl: ClassVar[Var[Theme]] = construct_theme_var("nightOwl")
+ nord: ClassVar[Var[Theme]] = construct_theme_var("nord")
+ okaidia: ClassVar[Var[Theme]] = construct_theme_var("okaidia")
+ one_dark: ClassVar[Var[Theme]] = construct_theme_var("oneDark")
+ one_light: ClassVar[Var[Theme]] = construct_theme_var("oneLight")
+ pojoaque: ClassVar[Var[Theme]] = construct_theme_var("pojoaque")
+ prism: ClassVar[Var[Theme]] = construct_theme_var("prism")
+ shades_of_purple: ClassVar[Var[Theme]] = construct_theme_var("shadesOfPurple")
+ solarized_dark_atom: ClassVar[Var[Theme]] = construct_theme_var("solarizedDarkAtom")
+ solarizedlight: ClassVar[Var[Theme]] = construct_theme_var("solarizedlight")
+ synthwave84: ClassVar[Var[Theme]] = construct_theme_var("synthwave84")
+ tomorrow: ClassVar[Var[Theme]] = construct_theme_var("tomorrow")
+ twilight: ClassVar[Var[Theme]] = construct_theme_var("twilight")
+ vs: ClassVar[Var[Theme]] = construct_theme_var("vs")
+ vs_dark: ClassVar[Var[Theme]] = construct_theme_var("vsDark")
+ vsc_dark_plus: ClassVar[Var[Theme]] = construct_theme_var("vscDarkPlus")
+ xonokai: ClassVar[Var[Theme]] = construct_theme_var("xonokai")
+ z_touch: ClassVar[Var[Theme]] = construct_theme_var("zTouch")
+
+
+for theme_name in dir(Theme):
+ if theme_name.startswith("_"):
+ continue
+ setattr(Theme, theme_name, getattr(Theme, theme_name)._replace(_var_type=Theme))
+
+
class CodeBlock(Component):
"""A code block."""
- library = "react-syntax-highlighter@15.5.0"
+ library = "react-syntax-highlighter@15.6.1"
tag = "PrismAsyncLight"
alias = "SyntaxHighlighter"
# The theme to use ("light" or "dark").
- theme: Var[LiteralCodeBlockTheme] = "one-light" # type: ignore
+ theme: Var[Union[Theme, str]] = Theme.one_light
# The language to use.
- language: Var[LiteralCodeLanguage] = "python" # type: ignore
+ language: Var[LiteralCodeLanguage] = Var.create("python")
# The code to display.
code: Var[str]
@@ -381,64 +411,55 @@ class CodeBlock(Component):
# Props passed down to the code tag.
code_tag_props: Var[Dict[str, str]]
- def _get_imports(self) -> imports.ImportDict:
- merged_imports = super()._get_imports()
- # Get all themes from a cond literal
- themes = re.findall(r"`(.*?)`", self.theme._var_name)
- if not themes:
- themes = [self.theme._var_name]
- merged_imports = imports.merge_imports(
- merged_imports,
- {
- f"react-syntax-highlighter/dist/cjs/styles/prism/{self.convert_theme_name(theme)}": {
- ImportVar(
- tag=format.to_camel_case(self.convert_theme_name(theme)),
- is_default=True,
- install=False,
- )
- }
- for theme in themes
- },
- )
+ # Whether a copy button should appear.
+ can_copy: Optional[bool] = False
+
+ # A custom copy button to override the default one.
+ copy_button: Optional[Union[bool, Component]] = None
+
+ def add_imports(self) -> ImportDict:
+ """Add imports for the CodeBlock component.
+
+ Returns:
+ The import dict.
+ """
+ imports_: ImportDict = {}
+
if (
self.language is not None
- and self.language._var_name in LiteralCodeLanguage.__args__ # type: ignore
+ and (language_without_quotes := str(self.language).replace('"', ""))
+ in LiteralCodeLanguage.__args__ # type: ignore
):
- merged_imports = imports.merge_imports(
- merged_imports,
- {
- f"react-syntax-highlighter/dist/cjs/languages/prism/{self.language._var_name}": {
- ImportVar(
- tag=format.to_camel_case(self.language._var_name),
- is_default=True,
- install=False,
- )
- }
- },
- )
- return merged_imports
+ imports_[
+ f"react-syntax-highlighter/dist/cjs/languages/prism/{language_without_quotes}"
+ ] = [
+ ImportVar(
+ tag=format.to_camel_case(language_without_quotes),
+ is_default=True,
+ install=False,
+ )
+ ]
+
+ return imports_
def _get_custom_code(self) -> Optional[str]:
if (
self.language is not None
- and self.language._var_name in LiteralCodeLanguage.__args__ # type: ignore
+ and (language_without_quotes := str(self.language).replace('"', ""))
+ in LiteralCodeLanguage.__args__ # type: ignore
):
- return f"{self.alias}.registerLanguage('{self.language._var_name}', {format.to_camel_case(self.language._var_name)})"
+ return f"{self.alias}.registerLanguage('{language_without_quotes}', {format.to_camel_case(language_without_quotes)})"
@classmethod
def create(
cls,
*children,
- can_copy: Optional[bool] = False,
- copy_button: Optional[Union[bool, Component]] = None,
**props,
):
"""Create a text component.
Args:
*children: The children of the component.
- can_copy: Whether a copy button should appears.
- copy_button: A custom copy button to override the default one.
**props: The props to pass to the component.
Returns:
@@ -446,15 +467,26 @@ class CodeBlock(Component):
"""
# This component handles style in a special prop.
custom_style = props.pop("custom_style", {})
+ can_copy = props.pop("can_copy", False)
+ copy_button = props.pop("copy_button", None)
if "theme" not in props:
# Default color scheme responds to global color mode.
- props["theme"] = color_mode_cond(light="one-light", dark="one-dark")
+ props["theme"] = color_mode_cond(
+ light=Theme.one_light,
+ dark=Theme.one_dark,
+ )
# react-syntax-highlighter doesnt have an explicit "light" or "dark" theme so we use one-light and one-dark
# themes respectively to ensure code compatibility.
if "theme" in props and not isinstance(props["theme"], Var):
- props["theme"] = cls.convert_theme_name(props["theme"])
+ props["theme"] = getattr(Theme, format.to_snake_case(props["theme"])) # type: ignore
+ console.deprecate(
+ feature_name="theme prop as string",
+ reason="Use code_block.themes instead.",
+ deprecation_version="0.6.0",
+ removal_version="0.7.0",
+ )
if can_copy:
code = children[0]
@@ -480,7 +512,7 @@ class CodeBlock(Component):
if children:
props["code"] = children[0]
if not isinstance(props["code"], Var):
- props["code"] = Var.create(props["code"], _var_is_string=True)
+ props["code"] = LiteralVar.create(props["code"])
# Create the component.
code_block = super().create(
@@ -493,33 +525,31 @@ class CodeBlock(Component):
else:
return code_block
- def add_style(self) -> Style | None:
+ def add_style(self):
"""Add style to the component."""
self.custom_style.update(self.style)
def _render(self):
out = super()._render()
- predicate, qmark, value = self.theme._var_name.partition("?")
- out.add_props(
- style=Var.create(
- format.to_camel_case(f"{predicate}{qmark}{value.replace('`', '')}"),
- _var_is_local=False,
- )
- ).remove_props("theme", "code")
- if self.code is not None:
- out.special_props.add(Var.create_safe(f"children={str(self.code)}"))
+
+ theme = self.theme
+
+ out.add_props(style=theme).remove_props("theme", "code").add_props(
+ children=self.code
+ )
+
return out
- @staticmethod
- def convert_theme_name(theme) -> str:
- """Convert theme names to appropriate names.
+ def _exclude_props(self) -> list[str]:
+ return ["can_copy", "copy_button"]
- Args:
- theme: The theme name.
- Returns:
- The right theme name.
- """
- if theme in ["light", "dark"]:
- return f"one-{theme}"
- return theme
+class CodeblockNamespace(ComponentNamespace):
+ """Namespace for the CodeBlock component."""
+
+ themes = Theme
+
+ __call__ = CodeBlock.create
+
+
+code_block = CodeblockNamespace()
diff --git a/reflex/components/datadisplay/code.pyi b/reflex/components/datadisplay/code.pyi
index f3aeb8e18..1e4f7110c 100644
--- a/reflex/components/datadisplay/code.pyi
+++ b/reflex/components/datadisplay/code.pyi
@@ -1,73 +1,18 @@
"""Stub file for reflex/components/datadisplay/code.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+import dataclasses
+from typing import Any, ClassVar, Dict, Literal, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-import re
-from typing import Dict, Literal, Optional, Union
-from reflex.components.chakra.forms import Button
-from reflex.components.chakra.layout import Box
-from reflex.components.chakra.media import Icon
-from reflex.components.component import Component
-from reflex.components.core.cond import color_mode_cond
+from reflex.components.component import Component, ComponentNamespace
from reflex.constants.colors import Color
-from reflex.event import set_clipboard
+from reflex.event import EventType
from reflex.style import Style
-from reflex.utils import format, imports
-from reflex.utils.imports import ImportVar
-from reflex.vars import Var
+from reflex.utils.imports import ImportDict
+from reflex.vars.base import Var
-LiteralCodeBlockTheme = Literal[
- "a11y-dark",
- "atom-dark",
- "cb",
- "coldark-cold",
- "coldark-dark",
- "coy",
- "coy-without-shadows",
- "darcula",
- "dark",
- "dracula",
- "duotone-dark",
- "duotone-earth",
- "duotone-forest",
- "duotone-light",
- "duotone-sea",
- "duotone-space",
- "funky",
- "ghcolors",
- "gruvbox-dark",
- "gruvbox-light",
- "holi-theme",
- "hopscotch",
- "light",
- "lucario",
- "material-dark",
- "material-light",
- "material-oceanic",
- "night-owl",
- "nord",
- "okaidia",
- "one-dark",
- "one-light",
- "pojoaque",
- "prism",
- "shades-of-purple",
- "solarized-dark-atom",
- "solarizedlight",
- "synthwave84",
- "tomorrow",
- "twilight",
- "vs",
- "vs-dark",
- "vsc-dark-plus",
- "xonokai",
- "z-touch",
-]
LiteralCodeLanguage = Literal[
"abap",
"abnf",
@@ -350,116 +295,351 @@ LiteralCodeLanguage = Literal[
"zig",
]
+def construct_theme_var(theme: str) -> Var[Theme]: ...
+@dataclasses.dataclass(init=False)
+class Theme:
+ a11y_dark: ClassVar[Var[Theme]] = construct_theme_var("a11yDark")
+ atom_dark: ClassVar[Var[Theme]] = construct_theme_var("atomDark")
+ cb: ClassVar[Var[Theme]] = construct_theme_var("cb")
+ coldark_cold: ClassVar[Var[Theme]] = construct_theme_var("coldarkCold")
+ coldark_dark: ClassVar[Var[Theme]] = construct_theme_var("coldarkDark")
+ coy: ClassVar[Var[Theme]] = construct_theme_var("coy")
+ coy_without_shadows: ClassVar[Var[Theme]] = construct_theme_var("coyWithoutShadows")
+ darcula: ClassVar[Var[Theme]] = construct_theme_var("darcula")
+ dark: ClassVar[Var[Theme]] = construct_theme_var("oneDark")
+ dracula: ClassVar[Var[Theme]] = construct_theme_var("dracula")
+ duotone_dark: ClassVar[Var[Theme]] = construct_theme_var("duotoneDark")
+ duotone_earth: ClassVar[Var[Theme]] = construct_theme_var("duotoneEarth")
+ duotone_forest: ClassVar[Var[Theme]] = construct_theme_var("duotoneForest")
+ duotone_light: ClassVar[Var[Theme]] = construct_theme_var("duotoneLight")
+ duotone_sea: ClassVar[Var[Theme]] = construct_theme_var("duotoneSea")
+ duotone_space: ClassVar[Var[Theme]] = construct_theme_var("duotoneSpace")
+ funky: ClassVar[Var[Theme]] = construct_theme_var("funky")
+ ghcolors: ClassVar[Var[Theme]] = construct_theme_var("ghcolors")
+ gruvbox_dark: ClassVar[Var[Theme]] = construct_theme_var("gruvboxDark")
+ gruvbox_light: ClassVar[Var[Theme]] = construct_theme_var("gruvboxLight")
+ holi_theme: ClassVar[Var[Theme]] = construct_theme_var("holiTheme")
+ hopscotch: ClassVar[Var[Theme]] = construct_theme_var("hopscotch")
+ light: ClassVar[Var[Theme]] = construct_theme_var("oneLight")
+ lucario: ClassVar[Var[Theme]] = construct_theme_var("lucario")
+ material_dark: ClassVar[Var[Theme]] = construct_theme_var("materialDark")
+ material_light: ClassVar[Var[Theme]] = construct_theme_var("materialLight")
+ material_oceanic: ClassVar[Var[Theme]] = construct_theme_var("materialOceanic")
+ night_owl: ClassVar[Var[Theme]] = construct_theme_var("nightOwl")
+ nord: ClassVar[Var[Theme]] = construct_theme_var("nord")
+ okaidia: ClassVar[Var[Theme]] = construct_theme_var("okaidia")
+ one_dark: ClassVar[Var[Theme]] = construct_theme_var("oneDark")
+ one_light: ClassVar[Var[Theme]] = construct_theme_var("oneLight")
+ pojoaque: ClassVar[Var[Theme]] = construct_theme_var("pojoaque")
+ prism: ClassVar[Var[Theme]] = construct_theme_var("prism")
+ shades_of_purple: ClassVar[Var[Theme]] = construct_theme_var("shadesOfPurple")
+ solarized_dark_atom: ClassVar[Var[Theme]] = construct_theme_var("solarizedDarkAtom")
+ solarizedlight: ClassVar[Var[Theme]] = construct_theme_var("solarizedlight")
+ synthwave84: ClassVar[Var[Theme]] = construct_theme_var("synthwave84")
+ tomorrow: ClassVar[Var[Theme]] = construct_theme_var("tomorrow")
+ twilight: ClassVar[Var[Theme]] = construct_theme_var("twilight")
+ vs: ClassVar[Var[Theme]] = construct_theme_var("vs")
+ vs_dark: ClassVar[Var[Theme]] = construct_theme_var("vsDark")
+ vsc_dark_plus: ClassVar[Var[Theme]] = construct_theme_var("vscDarkPlus")
+ xonokai: ClassVar[Var[Theme]] = construct_theme_var("xonokai")
+ z_touch: ClassVar[Var[Theme]] = construct_theme_var("zTouch")
+
+for theme_name in dir(Theme):
+ if theme_name.startswith("_"):
+ continue
+ setattr(Theme, theme_name, getattr(Theme, theme_name)._replace(_var_type=Theme))
+
class CodeBlock(Component):
+ def add_imports(self) -> ImportDict: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- can_copy: Optional[bool] = False,
- copy_button: Optional[Union[bool, Component]] = None,
- theme: Optional[
- Union[
- Var[
- Literal[
- "a11y-dark",
- "atom-dark",
- "cb",
- "coldark-cold",
- "coldark-dark",
- "coy",
- "coy-without-shadows",
- "darcula",
- "dark",
- "dracula",
- "duotone-dark",
- "duotone-earth",
- "duotone-forest",
- "duotone-light",
- "duotone-sea",
- "duotone-space",
- "funky",
- "ghcolors",
- "gruvbox-dark",
- "gruvbox-light",
- "holi-theme",
- "hopscotch",
- "light",
- "lucario",
- "material-dark",
- "material-light",
- "material-oceanic",
- "night-owl",
- "nord",
- "okaidia",
- "one-dark",
- "one-light",
- "pojoaque",
- "prism",
- "shades-of-purple",
- "solarized-dark-atom",
- "solarizedlight",
- "synthwave84",
- "tomorrow",
- "twilight",
- "vs",
- "vs-dark",
- "vsc-dark-plus",
- "xonokai",
- "z-touch",
- ]
- ],
- Literal[
- "a11y-dark",
- "atom-dark",
- "cb",
- "coldark-cold",
- "coldark-dark",
- "coy",
- "coy-without-shadows",
- "darcula",
- "dark",
- "dracula",
- "duotone-dark",
- "duotone-earth",
- "duotone-forest",
- "duotone-light",
- "duotone-sea",
- "duotone-space",
- "funky",
- "ghcolors",
- "gruvbox-dark",
- "gruvbox-light",
- "holi-theme",
- "hopscotch",
- "light",
- "lucario",
- "material-dark",
- "material-light",
- "material-oceanic",
- "night-owl",
- "nord",
- "okaidia",
- "one-dark",
- "one-light",
- "pojoaque",
- "prism",
- "shades-of-purple",
- "solarized-dark-atom",
- "solarizedlight",
- "synthwave84",
- "tomorrow",
- "twilight",
- "vs",
- "vs-dark",
- "vsc-dark-plus",
- "xonokai",
- "z-touch",
- ],
- ]
- ] = None,
+ theme: Optional[Union[Theme, Var[Union[Theme, str]], str]] = None,
language: Optional[
Union[
+ Literal[
+ "abap",
+ "abnf",
+ "actionscript",
+ "ada",
+ "agda",
+ "al",
+ "antlr4",
+ "apacheconf",
+ "apex",
+ "apl",
+ "applescript",
+ "aql",
+ "arduino",
+ "arff",
+ "asciidoc",
+ "asm6502",
+ "asmatmel",
+ "aspnet",
+ "autohotkey",
+ "autoit",
+ "avisynth",
+ "avro-idl",
+ "bash",
+ "basic",
+ "batch",
+ "bbcode",
+ "bicep",
+ "birb",
+ "bison",
+ "bnf",
+ "brainfuck",
+ "brightscript",
+ "bro",
+ "bsl",
+ "c",
+ "cfscript",
+ "chaiscript",
+ "cil",
+ "clike",
+ "clojure",
+ "cmake",
+ "cobol",
+ "coffeescript",
+ "concurnas",
+ "coq",
+ "core",
+ "cpp",
+ "crystal",
+ "csharp",
+ "cshtml",
+ "csp",
+ "css",
+ "css-extras",
+ "csv",
+ "cypher",
+ "d",
+ "dart",
+ "dataweave",
+ "dax",
+ "dhall",
+ "diff",
+ "django",
+ "dns-zone-file",
+ "docker",
+ "dot",
+ "ebnf",
+ "editorconfig",
+ "eiffel",
+ "ejs",
+ "elixir",
+ "elm",
+ "erb",
+ "erlang",
+ "etlua",
+ "excel-formula",
+ "factor",
+ "false",
+ "firestore-security-rules",
+ "flow",
+ "fortran",
+ "fsharp",
+ "ftl",
+ "gap",
+ "gcode",
+ "gdscript",
+ "gedcom",
+ "gherkin",
+ "git",
+ "glsl",
+ "gml",
+ "gn",
+ "go",
+ "go-module",
+ "graphql",
+ "groovy",
+ "haml",
+ "handlebars",
+ "haskell",
+ "haxe",
+ "hcl",
+ "hlsl",
+ "hoon",
+ "hpkp",
+ "hsts",
+ "http",
+ "ichigojam",
+ "icon",
+ "icu-message-format",
+ "idris",
+ "iecst",
+ "ignore",
+ "index",
+ "inform7",
+ "ini",
+ "io",
+ "j",
+ "java",
+ "javadoc",
+ "javadoclike",
+ "javascript",
+ "javastacktrace",
+ "jexl",
+ "jolie",
+ "jq",
+ "js-extras",
+ "js-templates",
+ "jsdoc",
+ "json",
+ "json5",
+ "jsonp",
+ "jsstacktrace",
+ "jsx",
+ "julia",
+ "keepalived",
+ "keyman",
+ "kotlin",
+ "kumir",
+ "kusto",
+ "latex",
+ "latte",
+ "less",
+ "lilypond",
+ "liquid",
+ "lisp",
+ "livescript",
+ "llvm",
+ "log",
+ "lolcode",
+ "lua",
+ "magma",
+ "makefile",
+ "markdown",
+ "markup",
+ "markup-templating",
+ "matlab",
+ "maxscript",
+ "mel",
+ "mermaid",
+ "mizar",
+ "mongodb",
+ "monkey",
+ "moonscript",
+ "n1ql",
+ "n4js",
+ "nand2tetris-hdl",
+ "naniscript",
+ "nasm",
+ "neon",
+ "nevod",
+ "nginx",
+ "nim",
+ "nix",
+ "nsis",
+ "objectivec",
+ "ocaml",
+ "opencl",
+ "openqasm",
+ "oz",
+ "parigp",
+ "parser",
+ "pascal",
+ "pascaligo",
+ "pcaxis",
+ "peoplecode",
+ "perl",
+ "php",
+ "php-extras",
+ "phpdoc",
+ "plsql",
+ "powerquery",
+ "powershell",
+ "processing",
+ "prolog",
+ "promql",
+ "properties",
+ "protobuf",
+ "psl",
+ "pug",
+ "puppet",
+ "pure",
+ "purebasic",
+ "purescript",
+ "python",
+ "q",
+ "qml",
+ "qore",
+ "qsharp",
+ "r",
+ "racket",
+ "reason",
+ "regex",
+ "rego",
+ "renpy",
+ "rest",
+ "rip",
+ "roboconf",
+ "robotframework",
+ "ruby",
+ "rust",
+ "sas",
+ "sass",
+ "scala",
+ "scheme",
+ "scss",
+ "shell-session",
+ "smali",
+ "smalltalk",
+ "smarty",
+ "sml",
+ "solidity",
+ "solution-file",
+ "soy",
+ "sparql",
+ "splunk-spl",
+ "sqf",
+ "sql",
+ "squirrel",
+ "stan",
+ "stylus",
+ "swift",
+ "systemd",
+ "t4-cs",
+ "t4-templating",
+ "t4-vb",
+ "tap",
+ "tcl",
+ "textile",
+ "toml",
+ "tremor",
+ "tsx",
+ "tt2",
+ "turtle",
+ "twig",
+ "typescript",
+ "typoscript",
+ "unrealscript",
+ "uorazor",
+ "uri",
+ "v",
+ "vala",
+ "vbnet",
+ "velocity",
+ "verilog",
+ "vhdl",
+ "vim",
+ "visual-basic",
+ "warpscript",
+ "wasm",
+ "web-idl",
+ "wiki",
+ "wolfram",
+ "wren",
+ "xeora",
+ "xml-doc",
+ "xojo",
+ "xquery",
+ "yaml",
+ "yang",
+ "zig",
+ ],
Var[
Literal[
"abap",
@@ -743,6 +923,77 @@ class CodeBlock(Component):
"zig",
]
],
+ ]
+ ] = None,
+ code: Optional[Union[Var[str], str]] = None,
+ show_line_numbers: Optional[Union[Var[bool], bool]] = None,
+ starting_line_number: Optional[Union[Var[int], int]] = None,
+ wrap_long_lines: Optional[Union[Var[bool], bool]] = None,
+ custom_style: Optional[Dict[str, Union[str, Var, Color]]] = None,
+ code_tag_props: Optional[Union[Dict[str, str], Var[Dict[str, str]]]] = None,
+ can_copy: Optional[bool] = None,
+ copy_button: Optional[Union[Component, bool]] = None,
+ style: Optional[Style] = None,
+ key: Optional[Any] = None,
+ id: Optional[Any] = None,
+ class_name: Optional[Any] = None,
+ autofocus: Optional[bool] = None,
+ custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
+ ) -> "CodeBlock":
+ """Create a text component.
+
+ Args:
+ *children: The children of the component.
+ theme: The theme to use ("light" or "dark").
+ language: The language to use.
+ code: The code to display.
+ show_line_numbers: If this is enabled line numbers will be shown next to the code block.
+ starting_line_number: The starting line number to use.
+ wrap_long_lines: Whether to wrap long lines.
+ custom_style: A custom style for the code block.
+ code_tag_props: Props passed down to the code tag.
+ can_copy: Whether a copy button should appear.
+ copy_button: A custom copy button to override the default one.
+ style: The style of the component.
+ key: A unique key for the component.
+ id: The id for the component.
+ class_name: The class name for the component.
+ autofocus: Whether the component should take the focus once the page is loaded
+ custom_attrs: custom attribute
+ **props: The props to pass to the component.
+
+ Returns:
+ The text component.
+ """
+ ...
+
+ def add_style(self): ...
+
+class CodeblockNamespace(ComponentNamespace):
+ themes = Theme
+
+ @staticmethod
+ def __call__(
+ *children,
+ theme: Optional[Union[Theme, Var[Union[Theme, str]], str]] = None,
+ language: Optional[
+ Union[
Literal[
"abap",
"abnf",
@@ -1024,6 +1275,289 @@ class CodeBlock(Component):
"yang",
"zig",
],
+ Var[
+ Literal[
+ "abap",
+ "abnf",
+ "actionscript",
+ "ada",
+ "agda",
+ "al",
+ "antlr4",
+ "apacheconf",
+ "apex",
+ "apl",
+ "applescript",
+ "aql",
+ "arduino",
+ "arff",
+ "asciidoc",
+ "asm6502",
+ "asmatmel",
+ "aspnet",
+ "autohotkey",
+ "autoit",
+ "avisynth",
+ "avro-idl",
+ "bash",
+ "basic",
+ "batch",
+ "bbcode",
+ "bicep",
+ "birb",
+ "bison",
+ "bnf",
+ "brainfuck",
+ "brightscript",
+ "bro",
+ "bsl",
+ "c",
+ "cfscript",
+ "chaiscript",
+ "cil",
+ "clike",
+ "clojure",
+ "cmake",
+ "cobol",
+ "coffeescript",
+ "concurnas",
+ "coq",
+ "core",
+ "cpp",
+ "crystal",
+ "csharp",
+ "cshtml",
+ "csp",
+ "css",
+ "css-extras",
+ "csv",
+ "cypher",
+ "d",
+ "dart",
+ "dataweave",
+ "dax",
+ "dhall",
+ "diff",
+ "django",
+ "dns-zone-file",
+ "docker",
+ "dot",
+ "ebnf",
+ "editorconfig",
+ "eiffel",
+ "ejs",
+ "elixir",
+ "elm",
+ "erb",
+ "erlang",
+ "etlua",
+ "excel-formula",
+ "factor",
+ "false",
+ "firestore-security-rules",
+ "flow",
+ "fortran",
+ "fsharp",
+ "ftl",
+ "gap",
+ "gcode",
+ "gdscript",
+ "gedcom",
+ "gherkin",
+ "git",
+ "glsl",
+ "gml",
+ "gn",
+ "go",
+ "go-module",
+ "graphql",
+ "groovy",
+ "haml",
+ "handlebars",
+ "haskell",
+ "haxe",
+ "hcl",
+ "hlsl",
+ "hoon",
+ "hpkp",
+ "hsts",
+ "http",
+ "ichigojam",
+ "icon",
+ "icu-message-format",
+ "idris",
+ "iecst",
+ "ignore",
+ "index",
+ "inform7",
+ "ini",
+ "io",
+ "j",
+ "java",
+ "javadoc",
+ "javadoclike",
+ "javascript",
+ "javastacktrace",
+ "jexl",
+ "jolie",
+ "jq",
+ "js-extras",
+ "js-templates",
+ "jsdoc",
+ "json",
+ "json5",
+ "jsonp",
+ "jsstacktrace",
+ "jsx",
+ "julia",
+ "keepalived",
+ "keyman",
+ "kotlin",
+ "kumir",
+ "kusto",
+ "latex",
+ "latte",
+ "less",
+ "lilypond",
+ "liquid",
+ "lisp",
+ "livescript",
+ "llvm",
+ "log",
+ "lolcode",
+ "lua",
+ "magma",
+ "makefile",
+ "markdown",
+ "markup",
+ "markup-templating",
+ "matlab",
+ "maxscript",
+ "mel",
+ "mermaid",
+ "mizar",
+ "mongodb",
+ "monkey",
+ "moonscript",
+ "n1ql",
+ "n4js",
+ "nand2tetris-hdl",
+ "naniscript",
+ "nasm",
+ "neon",
+ "nevod",
+ "nginx",
+ "nim",
+ "nix",
+ "nsis",
+ "objectivec",
+ "ocaml",
+ "opencl",
+ "openqasm",
+ "oz",
+ "parigp",
+ "parser",
+ "pascal",
+ "pascaligo",
+ "pcaxis",
+ "peoplecode",
+ "perl",
+ "php",
+ "php-extras",
+ "phpdoc",
+ "plsql",
+ "powerquery",
+ "powershell",
+ "processing",
+ "prolog",
+ "promql",
+ "properties",
+ "protobuf",
+ "psl",
+ "pug",
+ "puppet",
+ "pure",
+ "purebasic",
+ "purescript",
+ "python",
+ "q",
+ "qml",
+ "qore",
+ "qsharp",
+ "r",
+ "racket",
+ "reason",
+ "regex",
+ "rego",
+ "renpy",
+ "rest",
+ "rip",
+ "roboconf",
+ "robotframework",
+ "ruby",
+ "rust",
+ "sas",
+ "sass",
+ "scala",
+ "scheme",
+ "scss",
+ "shell-session",
+ "smali",
+ "smalltalk",
+ "smarty",
+ "sml",
+ "solidity",
+ "solution-file",
+ "soy",
+ "sparql",
+ "splunk-spl",
+ "sqf",
+ "sql",
+ "squirrel",
+ "stan",
+ "stylus",
+ "swift",
+ "systemd",
+ "t4-cs",
+ "t4-templating",
+ "t4-vb",
+ "tap",
+ "tcl",
+ "textile",
+ "toml",
+ "tremor",
+ "tsx",
+ "tt2",
+ "turtle",
+ "twig",
+ "typescript",
+ "typoscript",
+ "unrealscript",
+ "uorazor",
+ "uri",
+ "v",
+ "vala",
+ "vbnet",
+ "velocity",
+ "verilog",
+ "vhdl",
+ "vim",
+ "visual-basic",
+ "warpscript",
+ "wasm",
+ "web-idl",
+ "wiki",
+ "wolfram",
+ "wren",
+ "xeora",
+ "xml-doc",
+ "xojo",
+ "xquery",
+ "yaml",
+ "yang",
+ "zig",
+ ]
+ ],
]
] = None,
code: Optional[Union[Var[str], str]] = None,
@@ -1031,66 +1565,36 @@ class CodeBlock(Component):
starting_line_number: Optional[Union[Var[int], int]] = None,
wrap_long_lines: Optional[Union[Var[bool], bool]] = None,
custom_style: Optional[Dict[str, Union[str, Var, Color]]] = None,
- code_tag_props: Optional[Union[Var[Dict[str, str]], Dict[str, str]]] = None,
+ code_tag_props: Optional[Union[Dict[str, str], Var[Dict[str, str]]]] = None,
+ can_copy: Optional[bool] = None,
+ copy_button: Optional[Union[Component, bool]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "CodeBlock":
"""Create a text component.
Args:
*children: The children of the component.
- can_copy: Whether a copy button should appears.
- copy_button: A custom copy button to override the default one.
theme: The theme to use ("light" or "dark").
language: The language to use.
code: The code to display.
@@ -1099,6 +1603,8 @@ class CodeBlock(Component):
wrap_long_lines: Whether to wrap long lines.
custom_style: A custom style for the code block.
code_tag_props: Props passed down to the code tag.
+ can_copy: Whether a copy button should appear.
+ copy_button: A custom copy button to override the default one.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -1111,6 +1617,5 @@ class CodeBlock(Component):
The text component.
"""
...
- def add_style(self) -> Style | None: ...
- @staticmethod
- def convert_theme_name(theme) -> str: ...
+
+code_block = CodeblockNamespace()
diff --git a/reflex/components/datadisplay/dataeditor.py b/reflex/components/datadisplay/dataeditor.py
index ce9e3134f..27ca62d93 100644
--- a/reflex/components/datadisplay/dataeditor.py
+++ b/reflex/components/datadisplay/dataeditor.py
@@ -1,16 +1,22 @@
"""Data Editor component from glide-data-grid."""
+
from __future__ import annotations
from enum import Enum
-from typing import Any, Callable, Dict, List, Literal, Optional, Union
+from typing import Any, Dict, List, Literal, Optional, Tuple, Union
+
+from typing_extensions import TypedDict
from reflex.base import Base
from reflex.components.component import Component, NoSSRComponent
from reflex.components.literals import LiteralRowMarker
-from reflex.utils import console, format, imports, types
-from reflex.utils.imports import ImportVar
+from reflex.event import EventHandler, empty_event, identity_event
+from reflex.utils import console, format, types
+from reflex.utils.imports import ImportDict, ImportVar
from reflex.utils.serializers import serializer
-from reflex.vars import Var, get_unique_variable_name
+from reflex.vars import get_unique_variable_name
+from reflex.vars.base import Var
+from reflex.vars.sequence import ArrayVar
# TODO: Fix the serialization issue for custom types.
@@ -103,15 +109,87 @@ class DataEditorTheme(Base):
text_medium: Optional[str] = None
+class Bounds(TypedDict):
+ """The bounds of the group header."""
+
+ x: int
+ y: int
+ width: int
+ height: int
+
+
+class CompatSelection(TypedDict):
+ """The selection."""
+
+ items: list
+
+
+class Rectangle(TypedDict):
+ """The bounds of the group header."""
+
+ x: int
+ y: int
+ width: int
+ height: int
+
+
+class GridSelectionCurrent(TypedDict):
+ """The current selection."""
+
+ cell: tuple[int, int]
+ range: Rectangle
+ rangeStack: list[Rectangle]
+
+
+class GridSelection(TypedDict):
+ """The grid selection."""
+
+ current: Optional[GridSelectionCurrent]
+ columns: CompatSelection
+ rows: CompatSelection
+
+
+class GroupHeaderClickedEventArgs(TypedDict):
+ """The arguments for the group header clicked event."""
+
+ kind: str
+ group: str
+ location: tuple[int, int]
+ bounds: Bounds
+ isEdge: bool
+ shiftKey: bool
+ ctrlKey: bool
+ metaKey: bool
+ isTouch: bool
+ localEventX: int
+ localEventY: int
+ button: int
+ buttons: int
+ scrollEdge: tuple[int, int]
+
+
+class GridCell(TypedDict):
+ """The grid cell."""
+
+ span: Optional[List[int]]
+
+
+class GridColumn(TypedDict):
+ """The grid column."""
+
+ title: str
+ group: Optional[str]
+
+
class DataEditor(NoSSRComponent):
"""The DataEditor Component."""
tag = "DataEditor"
is_default = True
- library: str = "@glideapps/glide-data-grid@^5.3.0"
+ library: str = "@glideapps/glide-data-grid@^6.0.3"
lib_dependencies: List[str] = [
"lodash@^4.17.21",
- "marked@^4.0.10",
+ "marked@^14.1.2",
"react-responsive-carousel@^3.2.7",
]
@@ -128,7 +206,7 @@ class DataEditor(NoSSRComponent):
get_cell_content: Var[str]
# Allow selection for copying.
- get_cell_for_selection: Var[bool]
+ get_cells_for_selection: Var[bool]
# Allow paste.
on_paste: Var[bool]
@@ -205,65 +283,89 @@ class DataEditor(NoSSRComponent):
# global theme
theme: Var[Union[DataEditorTheme, Dict]]
- def _get_imports(self):
- return imports.merge_imports(
- super()._get_imports(),
- {
- "": {
- ImportVar(
- tag=f"{format.format_library_name(self.library)}/dist/index.css"
- )
- },
- self.library: {ImportVar(tag="GridCellKind")},
- "/utils/helpers/dataeditor.js": {
- ImportVar(
- tag=f"formatDataEditorCells", is_default=False, install=False
- ),
- },
- },
- )
+ # Fired when a cell is activated.
+ on_cell_activated: EventHandler[identity_event(Tuple[int, int])]
- def get_event_triggers(self) -> Dict[str, Callable]:
- """The event triggers of the component.
+ # Fired when a cell is clicked.
+ on_cell_clicked: EventHandler[identity_event(Tuple[int, int])]
+
+ # Fired when a cell is right-clicked.
+ on_cell_context_menu: EventHandler[identity_event(Tuple[int, int])]
+
+ # Fired when a cell is edited.
+ on_cell_edited: EventHandler[identity_event(Tuple[int, int], GridCell)]
+
+ # Fired when a group header is clicked.
+ on_group_header_clicked: EventHandler[identity_event(Tuple[int, int], GridCell)]
+
+ # Fired when a group header is right-clicked.
+ on_group_header_context_menu: EventHandler[
+ identity_event(int, GroupHeaderClickedEventArgs)
+ ]
+
+ # Fired when a group header is renamed.
+ on_group_header_renamed: EventHandler[identity_event(str, str)]
+
+ # Fired when a header is clicked.
+ on_header_clicked: EventHandler[identity_event(Tuple[int, int])]
+
+ # Fired when a header is right-clicked.
+ on_header_context_menu: EventHandler[identity_event(Tuple[int, int])]
+
+ # Fired when a header menu item is clicked.
+ on_header_menu_click: EventHandler[identity_event(int, Rectangle)]
+
+ # Fired when an item is hovered.
+ on_item_hovered: EventHandler[identity_event(Tuple[int, int])]
+
+ # Fired when a selection is deleted.
+ on_delete: EventHandler[identity_event(GridSelection)]
+
+ # Fired when editing is finished.
+ on_finished_editing: EventHandler[
+ identity_event(Union[GridCell, None], tuple[int, int])
+ ]
+
+ # Fired when a row is appended.
+ on_row_appended: EventHandler[empty_event]
+
+ # Fired when the selection is cleared.
+ on_selection_cleared: EventHandler[empty_event]
+
+ # Fired when a column is resized.
+ on_column_resize: EventHandler[identity_event(GridColumn, int)]
+
+ def add_imports(self) -> ImportDict:
+ """Add imports for the component.
Returns:
- The dict describing the event triggers.
+ The import dict.
"""
-
- def edit_sig(pos, data: dict[str, Any]):
- return [pos, data]
-
return {
- "on_cell_activated": lambda pos: [pos],
- "on_cell_clicked": lambda pos: [pos],
- "on_cell_context_menu": lambda pos: [pos],
- "on_cell_edited": edit_sig,
- "on_group_header_clicked": edit_sig,
- "on_group_header_context_menu": lambda grp_idx, data: [grp_idx, data],
- "on_group_header_renamed": lambda idx, val: [idx, val],
- "on_header_clicked": lambda pos: [pos],
- "on_header_context_menu": lambda pos: [pos],
- "on_header_menu_click": lambda col, pos: [col, pos],
- "on_item_hovered": lambda pos: [pos],
- "on_delete": lambda selection: [selection],
- "on_finished_editing": lambda new_value, movement: [new_value, movement],
- "on_row_appended": lambda: [],
- "on_selection_cleared": lambda: [],
- "on_column_resize": lambda col, width: [col, width],
+ "": f"{format.format_library_name(self.library)}/dist/index.css",
+ self.library: "GridCellKind",
+ "$/utils/helpers/dataeditor.js": ImportVar(
+ tag="formatDataEditorCells", is_default=False, install=False
+ ),
}
- def _get_hooks(self) -> str | None:
+ def add_hooks(self) -> list[str]:
+ """Get the hooks to render.
+
+ Returns:
+ The hooks to render.
+ """
# Define the id of the component in case multiple are used in the same page.
editor_id = get_unique_variable_name()
# Define the name of the getData callback associated with this component and assign to get_cell_content.
data_callback = f"getData_{editor_id}"
- self.get_cell_content = Var.create(data_callback, _var_is_local=False) # type: ignore
+ self.get_cell_content = Var(_js_expr=data_callback) # type: ignore
code = [f"function {data_callback}([col, row])" "{"]
- columns_path = f"{self.columns._var_full_name}"
- data_path = f"{self.data._var_full_name}"
+ columns_path = str(self.columns)
+ data_path = str(self.data)
code.extend(
[
@@ -272,7 +374,7 @@ class DataEditor(NoSSRComponent):
]
)
- return "\n".join(code)
+ return ["\n".join(code)]
@classmethod
def create(cls, *children, **props) -> Component:
@@ -292,15 +394,15 @@ class DataEditor(NoSSRComponent):
columns = props.get("columns", [])
data = props.get("data", [])
- rows = props.get("rows", None)
+ rows = props.get("rows")
# If rows is not provided, determine from data.
if rows is None:
- props["rows"] = (
- data.length() # BaseVar.create(value=f"{data}.length()", is_local=False)
- if isinstance(data, Var)
- else len(data)
- )
+ if isinstance(data, Var) and not isinstance(data, ArrayVar):
+ raise ValueError(
+ "DataEditor data must be an ArrayVar if rows is not provided."
+ )
+ props["rows"] = data.length() if isinstance(data, Var) else len(data)
if not isinstance(columns, Var) and len(columns):
if (
@@ -322,7 +424,7 @@ class DataEditor(NoSSRComponent):
props["theme"] = DataEditorTheme(**theme)
# Allow by default to select a region of cells in the grid.
- props.setdefault("get_cell_for_selection", True)
+ props.setdefault("get_cells_for_selection", True)
# Disable on_paste by default if not provided.
props.setdefault("on_paste", False)
@@ -360,43 +462,6 @@ class DataEditor(NoSSRComponent):
}
-# try:
-# pass
-
-# # def format_dataframe_values(df: DataFrame) -> list[list[Any]]:
-# # """Format dataframe values to a list of lists.
-
-# # Args:
-# # df: The dataframe to format.
-
-# # Returns:
-# # The dataframe as a list of lists.
-# # """
-# # return [
-# # [str(d) if isinstance(d, (list, tuple)) else d for d in data]
-# # for data in list(df.values.tolist())
-# # ]
-# # ...
-
-# # @serializer
-# # def serialize_dataframe(df: DataFrame) -> dict:
-# # """Serialize a pandas dataframe.
-
-# # Args:
-# # df: The dataframe to serialize.
-
-# # Returns:
-# # The serialized dataframe.
-# # """
-# # return {
-# # "columns": df.columns.tolist(),
-# # "data": format_dataframe_values(df),
-# # }
-
-# except ImportError:
-# pass
-
-
@serializer
def serialize_dataeditortheme(theme: DataEditorTheme):
"""The serializer for the data editor theme.
@@ -407,6 +472,10 @@ def serialize_dataeditortheme(theme: DataEditorTheme):
Returns:
The serialized theme.
"""
- return format.json_dumps(
- {format.to_camel_case(k): v for k, v in theme.__dict__.items() if v is not None}
- )
+ return {
+ format.to_camel_case(k): v for k, v in theme.__dict__.items() if v is not None
+ }
+
+
+data_editor = DataEditor.create
+data_editor_theme = DataEditorTheme
diff --git a/reflex/components/datadisplay/dataeditor.pyi b/reflex/components/datadisplay/dataeditor.pyi
index fe8c52aad..b1ff93c38 100644
--- a/reflex/components/datadisplay/dataeditor.pyi
+++ b/reflex/components/datadisplay/dataeditor.pyi
@@ -1,21 +1,20 @@
"""Stub file for reflex/components/datadisplay/dataeditor.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
from enum import Enum
-from typing import Any, Callable, Dict, List, Literal, Optional, Union
+from typing import Any, Dict, List, Literal, Optional, Union, overload
+
+from typing_extensions import TypedDict
+
from reflex.base import Base
-from reflex.components.component import Component, NoSSRComponent
-from reflex.components.literals import LiteralRowMarker
-from reflex.utils import console, format, imports, types
-from reflex.utils.imports import ImportVar
+from reflex.components.component import NoSSRComponent
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.utils.imports import ImportDict
from reflex.utils.serializers import serializer
-from reflex.vars import Var, get_unique_variable_name
+from reflex.vars.base import Var
class GridColumnIcons(Enum):
Array = "array"
@@ -79,8 +78,57 @@ class DataEditorTheme(Base):
text_light: Optional[str]
text_medium: Optional[str]
+class Bounds(TypedDict):
+ x: int
+ y: int
+ width: int
+ height: int
+
+class CompatSelection(TypedDict):
+ items: list
+
+class Rectangle(TypedDict):
+ x: int
+ y: int
+ width: int
+ height: int
+
+class GridSelectionCurrent(TypedDict):
+ cell: tuple[int, int]
+ range: Rectangle
+ rangeStack: list[Rectangle]
+
+class GridSelection(TypedDict):
+ current: Optional[GridSelectionCurrent]
+ columns: CompatSelection
+ rows: CompatSelection
+
+class GroupHeaderClickedEventArgs(TypedDict):
+ kind: str
+ group: str
+ location: tuple[int, int]
+ bounds: Bounds
+ isEdge: bool
+ shiftKey: bool
+ ctrlKey: bool
+ metaKey: bool
+ isTouch: bool
+ localEventX: int
+ localEventY: int
+ button: int
+ buttons: int
+ scrollEdge: tuple[int, int]
+
+class GridCell(TypedDict):
+ span: Optional[List[int]]
+
+class GridColumn(TypedDict):
+ title: str
+ group: Optional[str]
+
class DataEditor(NoSSRComponent):
- def get_event_triggers(self) -> Dict[str, Callable]: ...
+ def add_imports(self) -> ImportDict: ...
+ def add_hooks(self) -> list[str]: ...
@overload
@classmethod
def create( # type: ignore
@@ -88,11 +136,11 @@ class DataEditor(NoSSRComponent):
*children,
rows: Optional[Union[Var[int], int]] = None,
columns: Optional[
- Union[Var[List[Dict[str, Any]]], List[Dict[str, Any]]]
+ Union[List[Dict[str, Any]], Var[List[Dict[str, Any]]]]
] = None,
- data: Optional[Union[Var[List[List[Any]]], List[List[Any]]]] = None,
+ data: Optional[Union[List[List[Any]], Var[List[List[Any]]]]] = None,
get_cell_content: Optional[Union[Var[str], str]] = None,
- get_cell_for_selection: Optional[Union[Var[bool], bool]] = None,
+ get_cells_for_selection: Optional[Union[Var[bool], bool]] = None,
on_paste: Optional[Union[Var[bool], bool]] = None,
draw_focus_ring: Optional[Union[Var[bool], bool]] = None,
fixed_shadow_x: Optional[Union[Var[bool], bool]] = None,
@@ -106,8 +154,8 @@ class DataEditor(NoSSRComponent):
row_height: Optional[Union[Var[int], int]] = None,
row_markers: Optional[
Union[
- Var[Literal["none", "number", "checkbox", "both", "clickable-number"]],
- Literal["none", "number", "checkbox", "both", "clickable-number"],
+ Literal["both", "checkbox", "clickable-number", "none", "number"],
+ Var[Literal["both", "checkbox", "clickable-number", "none", "number"]],
]
] = None,
row_marker_start_index: Optional[Union[Var[int], int]] = None,
@@ -117,8 +165,8 @@ class DataEditor(NoSSRComponent):
vertical_border: Optional[Union[Var[bool], bool]] = None,
column_select: Optional[
Union[
- Var[Literal["none", "single", "multi"]],
- Literal["none", "single", "multi"],
+ Literal["multi", "none", "single"],
+ Var[Literal["multi", "none", "single"]],
]
] = None,
prevent_diagonal_scrolling: Optional[Union[Var[bool], bool]] = None,
@@ -127,7 +175,7 @@ class DataEditor(NoSSRComponent):
scroll_offset_x: Optional[Union[Var[int], int]] = None,
scroll_offset_y: Optional[Union[Var[int], int]] = None,
theme: Optional[
- Union[Var[Union[DataEditorTheme, Dict]], Union[DataEditorTheme, Dict]]
+ Union[DataEditorTheme, Dict, Var[Union[DataEditorTheme, Dict]]]
] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
@@ -135,55 +183,42 @@ class DataEditor(NoSSRComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_cell_activated: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_cell_clicked: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_cell_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_cell_edited: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_column_resize: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_delete: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_cell_activated: Optional[EventType[tuple[int, int]]] = None,
+ on_cell_clicked: Optional[EventType[tuple[int, int]]] = None,
+ on_cell_context_menu: Optional[EventType[tuple[int, int]]] = None,
+ on_cell_edited: Optional[EventType[tuple[int, int], GridCell]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_column_resize: Optional[EventType[GridColumn, int]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_delete: Optional[EventType[GridSelection]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
on_finished_editing: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_group_header_clicked: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
+ EventType[Union[GridCell, None], tuple[int, int]]
] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_group_header_clicked: Optional[EventType[tuple[int, int], GridCell]] = None,
on_group_header_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
+ EventType[int, GroupHeaderClickedEventArgs]
] = None,
- on_group_header_renamed: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_header_clicked: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_header_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_header_menu_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_item_hovered: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_row_appended: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_selection_cleared: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_group_header_renamed: Optional[EventType[str, str]] = None,
+ on_header_clicked: Optional[EventType[tuple[int, int]]] = None,
+ on_header_context_menu: Optional[EventType[tuple[int, int]]] = None,
+ on_header_menu_click: Optional[EventType[int, Rectangle]] = None,
+ on_item_hovered: Optional[EventType[tuple[int, int]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_row_appended: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_selection_cleared: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DataEditor":
"""Create the DataEditor component.
@@ -193,7 +228,7 @@ class DataEditor(NoSSRComponent):
columns: Headers of the columns for the data grid.
data: The data.
get_cell_content: The name of the callback used to find the data to display.
- get_cell_for_selection: Allow selection for copying.
+ get_cells_for_selection: Allow selection for copying.
on_paste: Allow paste.
draw_focus_ring: Controls the drawing of the focus ring.
fixed_shadow_x: Enables or disables the overlay shadow when scrolling horizontally.
@@ -218,6 +253,22 @@ class DataEditor(NoSSRComponent):
scroll_offset_x: Initial scroll offset on the horizontal axis.
scroll_offset_y: Initial scroll offset on the vertical axis.
theme: global theme
+ on_cell_activated: Fired when a cell is activated.
+ on_cell_clicked: Fired when a cell is clicked.
+ on_cell_context_menu: Fired when a cell is right-clicked.
+ on_cell_edited: Fired when a cell is edited.
+ on_group_header_clicked: Fired when a group header is clicked.
+ on_group_header_context_menu: Fired when a group header is right-clicked.
+ on_group_header_renamed: Fired when a group header is renamed.
+ on_header_clicked: Fired when a header is clicked.
+ on_header_context_menu: Fired when a header is right-clicked.
+ on_header_menu_click: Fired when a header menu item is clicked.
+ on_item_hovered: Fired when an item is hovered.
+ on_delete: Fired when a selection is deleted.
+ on_finished_editing: Fired when editing is finished.
+ on_row_appended: Fired when a row is appended.
+ on_selection_cleared: Fired when the selection is cleared.
+ on_column_resize: Fired when a column is resized.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -236,3 +287,6 @@ class DataEditor(NoSSRComponent):
@serializer
def serialize_dataeditortheme(theme: DataEditorTheme): ...
+
+data_editor = DataEditor.create
+data_editor_theme = DataEditorTheme
diff --git a/reflex/components/datadisplay/logo.py b/reflex/components/datadisplay/logo.py
index 1a56cfd88..beb9b9d10 100644
--- a/reflex/components/datadisplay/logo.py
+++ b/reflex/components/datadisplay/logo.py
@@ -1,4 +1,5 @@
"""A Reflex logo component."""
+
import reflex as rx
@@ -11,31 +12,33 @@ def logo(**props):
Returns:
The logo component.
"""
- light_mode_logo = """
-
-
-
-
-
-
- """
- dark_mode_logo = """
-
-
-
-
-
-
- """
+ def logo_path(d):
+ return rx.el.svg.path(
+ d=d,
+ fill=rx.color_mode_cond("#110F1F", "white"),
+ )
+
+ paths = [
+ "M0 11.5999V0.399902H8.96V4.8799H6.72V2.6399H2.24V4.8799H6.72V7.1199H2.24V11.5999H0ZM6.72 11.5999V7.1199H8.96V11.5999H6.72Z",
+ "M11.2 11.5999V0.399902H17.92V2.6399H13.44V4.8799H17.92V7.1199H13.44V9.3599H17.92V11.5999H11.2Z",
+ "M20.16 11.5999V0.399902H26.88V2.6399H22.4V4.8799H26.88V7.1199H22.4V11.5999H20.16Z",
+ "M29.12 11.5999V0.399902H31.36V9.3599H35.84V11.5999H29.12Z",
+ "M38.08 11.5999V0.399902H44.8V2.6399H40.32V4.8799H44.8V7.1199H40.32V9.3599H44.8V11.5999H38.08Z",
+ "M47.04 4.8799V0.399902H49.28V4.8799H47.04ZM53.76 4.8799V0.399902H56V4.8799H53.76ZM49.28 7.1199V4.8799H53.76V7.1199H49.28ZM47.04 11.5999V7.1199H49.28V11.5999H47.04ZM53.76 11.5999V7.1199H56V11.5999H53.76Z",
+ ]
return rx.center(
rx.link(
rx.hstack(
"Built with ",
- rx.color_mode_cond(
- rx.html(light_mode_logo),
- rx.html(dark_mode_logo),
+ rx.el.svg(
+ *[logo_path(d) for d in paths],
+ width="56",
+ height="12",
+ viewBox="0 0 56 12",
+ fill="none",
+ xmlns="http://www.w3.org/2000/svg",
),
text_align="center",
align="center",
diff --git a/reflex/components/datadisplay/shiki_code_block.py b/reflex/components/datadisplay/shiki_code_block.py
new file mode 100644
index 000000000..07f09c6f6
--- /dev/null
+++ b/reflex/components/datadisplay/shiki_code_block.py
@@ -0,0 +1,846 @@
+"""Shiki syntax hghlighter component."""
+
+from __future__ import annotations
+
+import re
+from collections import defaultdict
+from typing import Any, Literal, Optional, Union
+
+from reflex.base import Base
+from reflex.components.component import Component, ComponentNamespace
+from reflex.components.core.colors import color
+from reflex.components.core.cond import color_mode_cond
+from reflex.components.el.elements.forms import Button
+from reflex.components.lucide.icon import Icon
+from reflex.components.props import NoExtrasAllowedProps
+from reflex.components.radix.themes.layout.box import Box
+from reflex.event import call_script, set_clipboard
+from reflex.style import Style
+from reflex.utils.exceptions import VarTypeError
+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() -> Any:
+ """Copy script for the code block and modify the child SVG element.
+
+
+ Returns:
+ Any: The result of calling the script.
+ """
+ return call_script(
+ f"""
+// Event listener for the parent click
+document.addEventListener('click', function(event) {{
+ // Find the closest button (parent element)
+ const parent = event.target.closest('button');
+ // If the parent is found
+ if (parent) {{
+ // Find the SVG element within the parent
+ const svgIcon = parent.querySelector('svg');
+ // If the SVG exists, proceed with the script
+ if (svgIcon) {{
+ const originalPath = svgIcon.innerHTML;
+ const checkmarkPath = ' '; // Checkmark SVG path
+ function transition(element, scale, opacity) {{
+ element.style.transform = `scale(${{scale}})`;
+ element.style.opacity = opacity;
+ }}
+ // Animate the SVG
+ transition(svgIcon, 0, '0');
+ setTimeout(() => {{
+ svgIcon.innerHTML = checkmarkPath; // Replace content with checkmark
+ svgIcon.setAttribute('viewBox', '0 0 24 24'); // Adjust viewBox if necessary
+ transition(svgIcon, 1, '1');
+ setTimeout(() => {{
+ transition(svgIcon, 0, '0');
+ setTimeout(() => {{
+ svgIcon.innerHTML = originalPath; // Restore original SVG content
+ transition(svgIcon, 1, '1');
+ }}, 125);
+ }}, 600);
+ }}, 125);
+ }} else {{
+ // console.error('SVG element not found within the parent.');
+ }}
+ }} else {{
+ // console.error('Parent element not found.');
+ }}
+}});
+"""
+ )
+
+
+SHIKIJS_TRANSFORMER_FNS = {
+ "transformerNotationDiff",
+ "transformerNotationHighlight",
+ "transformerNotationWordHighlight",
+ "transformerNotationFocus",
+ "transformerNotationErrorLevel",
+ "transformerRenderWhitespace",
+ "transformerMetaHighlight",
+ "transformerMetaWordHighlight",
+ "transformerCompactLineOptions",
+ # TODO: this transformer when included adds a weird behavior which removes other code lines. Need to figure out why.
+ # "transformerRemoveLineBreak",
+ "transformerRemoveNotationEscape",
+}
+LINE_NUMBER_STYLING = {
+ "code": {
+ "counter-reset": "step",
+ "counter-increment": "step 0",
+ "display": "grid",
+ "line-height": "1.7",
+ "font-size": "0.875em",
+ },
+ "code .line::before": {
+ "content": "counter(step)",
+ "counter-increment": "step",
+ "width": "1rem",
+ "margin-right": "1.5rem",
+ "display": "inline-block",
+ "text-align": "right",
+ "color": "rgba(115,138,148,.4)",
+ },
+}
+BOX_PARENT_STYLING = {
+ "pre": {
+ "margin": "0",
+ "padding": "24px",
+ "background": "transparent",
+ "overflow-x": "auto",
+ "border-radius": "6px",
+ },
+}
+
+THEME_MAPPING = {
+ "light": "one-light",
+ "dark": "one-dark-pro",
+ "a11y-dark": "github-dark",
+}
+LANGUAGE_MAPPING = {"bash": "shellscript"}
+LiteralCodeLanguage = Literal[
+ "abap",
+ "actionscript-3",
+ "ada",
+ "angular-html",
+ "angular-ts",
+ "apache",
+ "apex",
+ "apl",
+ "applescript",
+ "ara",
+ "asciidoc",
+ "asm",
+ "astro",
+ "awk",
+ "ballerina",
+ "bat",
+ "beancount",
+ "berry",
+ "bibtex",
+ "bicep",
+ "blade",
+ "c",
+ "cadence",
+ "clarity",
+ "clojure",
+ "cmake",
+ "cobol",
+ "codeowners",
+ "codeql",
+ "coffee",
+ "common-lisp",
+ "coq",
+ "cpp",
+ "crystal",
+ "csharp",
+ "css",
+ "csv",
+ "cue",
+ "cypher",
+ "d",
+ "dart",
+ "dax",
+ "desktop",
+ "diff",
+ "docker",
+ "dotenv",
+ "dream-maker",
+ "edge",
+ "elixir",
+ "elm",
+ "emacs-lisp",
+ "erb",
+ "erlang",
+ "fennel",
+ "fish",
+ "fluent",
+ "fortran-fixed-form",
+ "fortran-free-form",
+ "fsharp",
+ "gdresource",
+ "gdscript",
+ "gdshader",
+ "genie",
+ "gherkin",
+ "git-commit",
+ "git-rebase",
+ "gleam",
+ "glimmer-js",
+ "glimmer-ts",
+ "glsl",
+ "gnuplot",
+ "go",
+ "graphql",
+ "groovy",
+ "hack",
+ "haml",
+ "handlebars",
+ "haskell",
+ "haxe",
+ "hcl",
+ "hjson",
+ "hlsl",
+ "html",
+ "html-derivative",
+ "http",
+ "hxml",
+ "hy",
+ "imba",
+ "ini",
+ "java",
+ "javascript",
+ "jinja",
+ "jison",
+ "json",
+ "json5",
+ "jsonc",
+ "jsonl",
+ "jsonnet",
+ "jssm",
+ "jsx",
+ "julia",
+ "kotlin",
+ "kusto",
+ "latex",
+ "lean",
+ "less",
+ "liquid",
+ "log",
+ "logo",
+ "lua",
+ "luau",
+ "make",
+ "markdown",
+ "marko",
+ "matlab",
+ "mdc",
+ "mdx",
+ "mermaid",
+ "mojo",
+ "move",
+ "narrat",
+ "nextflow",
+ "nginx",
+ "nim",
+ "nix",
+ "nushell",
+ "objective-c",
+ "objective-cpp",
+ "ocaml",
+ "pascal",
+ "perl",
+ "php",
+ "plain",
+ "plsql",
+ "po",
+ "postcss",
+ "powerquery",
+ "powershell",
+ "prisma",
+ "prolog",
+ "proto",
+ "pug",
+ "puppet",
+ "purescript",
+ "python",
+ "qml",
+ "qmldir",
+ "qss",
+ "r",
+ "racket",
+ "raku",
+ "razor",
+ "reg",
+ "regexp",
+ "rel",
+ "riscv",
+ "rst",
+ "ruby",
+ "rust",
+ "sas",
+ "sass",
+ "scala",
+ "scheme",
+ "scss",
+ "shaderlab",
+ "shellscript",
+ "shellsession",
+ "smalltalk",
+ "solidity",
+ "soy",
+ "sparql",
+ "splunk",
+ "sql",
+ "ssh-config",
+ "stata",
+ "stylus",
+ "svelte",
+ "swift",
+ "system-verilog",
+ "systemd",
+ "tasl",
+ "tcl",
+ "templ",
+ "terraform",
+ "tex",
+ "toml",
+ "ts-tags",
+ "tsv",
+ "tsx",
+ "turtle",
+ "twig",
+ "typescript",
+ "typespec",
+ "typst",
+ "v",
+ "vala",
+ "vb",
+ "verilog",
+ "vhdl",
+ "viml",
+ "vue",
+ "vue-html",
+ "vyper",
+ "wasm",
+ "wenyan",
+ "wgsl",
+ "wikitext",
+ "wolfram",
+ "xml",
+ "xsl",
+ "yaml",
+ "zenscript",
+ "zig",
+]
+LiteralCodeTheme = Literal[
+ "andromeeda",
+ "aurora-x",
+ "ayu-dark",
+ "catppuccin-frappe",
+ "catppuccin-latte",
+ "catppuccin-macchiato",
+ "catppuccin-mocha",
+ "dark-plus",
+ "dracula",
+ "dracula-soft",
+ "everforest-dark",
+ "everforest-light",
+ "github-dark",
+ "github-dark-default",
+ "github-dark-dimmed",
+ "github-dark-high-contrast",
+ "github-light",
+ "github-light-default",
+ "github-light-high-contrast",
+ "houston",
+ "laserwave",
+ "light-plus",
+ "material-theme",
+ "material-theme-darker",
+ "material-theme-lighter",
+ "material-theme-ocean",
+ "material-theme-palenight",
+ "min-dark",
+ "min-light",
+ "monokai",
+ "night-owl",
+ "nord",
+ "one-dark-pro",
+ "one-light",
+ "plastic",
+ "poimandres",
+ "red",
+ # rose-pine themes dont work with the current version of shikijs transformers
+ # https://github.com/shikijs/shiki/issues/730
+ "rose-pine",
+ "rose-pine-dawn",
+ "rose-pine-moon",
+ "slack-dark",
+ "slack-ochin",
+ "snazzy-light",
+ "solarized-dark",
+ "solarized-light",
+ "synthwave-84",
+ "tokyo-night",
+ "vesper",
+ "vitesse-black",
+ "vitesse-dark",
+ "vitesse-light",
+]
+
+
+class Position(NoExtrasAllowedProps):
+ """Position of the decoration."""
+
+ line: int
+ character: int
+
+
+class ShikiDecorations(NoExtrasAllowedProps):
+ """Decorations for the code block."""
+
+ start: Union[int, Position]
+ end: Union[int, Position]
+ tag_name: str = "span"
+ properties: dict[str, Any] = {}
+ always_wrap: bool = False
+
+
+class ShikiBaseTransformers(Base):
+ """Base for creating transformers."""
+
+ library: str
+ fns: list[FunctionStringVar]
+ style: Optional[Style]
+
+
+class ShikiJsTransformer(ShikiBaseTransformers):
+ """A Wrapped shikijs transformer."""
+
+ library: str = "@shikijs/transformers"
+ fns: list[FunctionStringVar] = [
+ FunctionStringVar.create(fn) for fn in SHIKIJS_TRANSFORMER_FNS
+ ]
+ style: Optional[Style] = Style(
+ {
+ "code": {"line-height": "1.7", "font-size": "0.875em", "display": "grid"},
+ # Diffs
+ ".diff": {
+ "margin": "0 -24px",
+ "padding": "0 24px",
+ "width": "calc(100% + 48px)",
+ "display": "inline-block",
+ },
+ ".diff.add": {
+ "background-color": "rgba(16, 185, 129, .14)",
+ "position": "relative",
+ },
+ ".diff.remove": {
+ "background-color": "rgba(244, 63, 94, .14)",
+ "opacity": "0.7",
+ "position": "relative",
+ },
+ ".diff.remove:after": {
+ "position": "absolute",
+ "left": "10px",
+ "content": "'-'",
+ "color": "#b34e52",
+ },
+ ".diff.add:after": {
+ "position": "absolute",
+ "left": "10px",
+ "content": "'+'",
+ "color": "#18794e",
+ },
+ # Highlight
+ ".highlighted": {
+ "background-color": "rgba(142, 150, 170, .14)",
+ "margin": "0 -24px",
+ "padding": "0 24px",
+ "width": "calc(100% + 48px)",
+ "display": "inline-block",
+ },
+ ".highlighted.error": {
+ "background-color": "rgba(244, 63, 94, .14)",
+ },
+ ".highlighted.warning": {
+ "background-color": "rgba(234, 179, 8, .14)",
+ },
+ # Highlighted Word
+ ".highlighted-word": {
+ "background-color": color("gray", 2),
+ "border": f"1px solid {color('gray', 5)}",
+ "padding": "1px 3px",
+ "margin": "-1px -3px",
+ "border-radius": "4px",
+ },
+ # Focused Lines
+ ".has-focused .line:not(.focused)": {
+ "opacity": "0.7",
+ "filter": "blur(0.095rem)",
+ "transition": "filter .35s, opacity .35s",
+ },
+ ".has-focused:hover .line:not(.focused)": {
+ "opacity": "1",
+ "filter": "none",
+ },
+ # White Space
+ # ".tab, .space": {
+ # "position": "relative",
+ # },
+ # ".tab::before": {
+ # "content": "'⇥'",
+ # "position": "absolute",
+ # "opacity": "0.3",
+ # },
+ # ".space::before": {
+ # "content": "'·'",
+ # "position": "absolute",
+ # "opacity": "0.3",
+ # },
+ }
+ )
+
+ def __init__(self, **kwargs):
+ """Initialize the transformer.
+
+ Args:
+ kwargs: Kwargs to initialize the props.
+
+ """
+ fns = kwargs.pop("fns", None)
+ style = kwargs.pop("style", None)
+ if fns:
+ kwargs["fns"] = [
+ (
+ FunctionStringVar.create(x)
+ if not isinstance(x, FunctionStringVar)
+ else x
+ )
+ for x in fns
+ ]
+
+ if style:
+ kwargs["style"] = Style(style)
+ super().__init__(**kwargs)
+
+
+class ShikiCodeBlock(Component):
+ """A Code block."""
+
+ library = "/components/shiki/code"
+
+ tag = "Code"
+
+ alias = "ShikiCode"
+
+ lib_dependencies: list[str] = ["shiki"]
+
+ # The language to use.
+ language: Var[LiteralCodeLanguage] = Var.create("python")
+
+ # The theme to use ("light" or "dark").
+ theme: Var[LiteralCodeTheme] = Var.create("one-light")
+
+ # The set of themes to use for different modes.
+ themes: Var[Union[list[dict[str, Any]], dict[str, str]]]
+
+ # The code to display.
+ code: Var[str]
+
+ # The transformers to use for the syntax highlighter.
+ transformers: Var[list[Union[ShikiBaseTransformers, dict[str, Any]]]] = Var.create(
+ []
+ )
+
+ # The decorations to use for the syntax highlighter.
+ decorations: Var[list[ShikiDecorations]] = Var.create([])
+
+ @classmethod
+ def create(
+ cls,
+ *children,
+ **props,
+ ) -> Component:
+ """Create a code block component using [shiki syntax highlighter](https://shiki.matsu.io/).
+
+ Args:
+ *children: The children of the component.
+ **props: The props to pass to the component.
+
+ Returns:
+ The code block component.
+ """
+ # Separate props for the code block and the wrapper
+ code_block_props = {}
+ code_wrapper_props = {}
+ decorations = props.pop("decorations", [])
+
+ class_props = cls.get_props()
+
+ # Distribute props between the code block and wrapper
+ for key, value in props.items():
+ (code_block_props if key in class_props else code_wrapper_props)[key] = (
+ value
+ )
+
+ # cast decorations into ShikiDecorations.
+ decorations = [
+ ShikiDecorations(**decoration)
+ if not isinstance(decoration, ShikiDecorations)
+ else decoration
+ for decoration in decorations
+ ]
+ code_block_props["decorations"] = decorations
+
+ code_block_props["code"] = children[0]
+ code_block = super().create(**code_block_props)
+
+ transformer_styles = {}
+ # Collect styles from transformers and wrapper
+ for transformer in code_block.transformers._var_value: # type: ignore
+ if isinstance(transformer, ShikiBaseTransformers) and transformer.style:
+ transformer_styles.update(transformer.style)
+ transformer_styles.update(code_wrapper_props.pop("style", {}))
+
+ return Box.create(
+ code_block,
+ *children[1:],
+ style=Style({**transformer_styles, **BOX_PARENT_STYLING}),
+ **code_wrapper_props,
+ )
+
+ def add_imports(self) -> dict[str, list[str]]:
+ """Add the necessary imports.
+ We add all referenced transformer functions as imports from their corresponding
+ libraries.
+
+ Returns:
+ Imports for the component.
+ """
+ imports = defaultdict(list)
+ for transformer in self.transformers._var_value:
+ if isinstance(transformer, ShikiBaseTransformers):
+ imports[transformer.library].extend(
+ [ImportVar(tag=str(fn)) for fn in transformer.fns]
+ )
+ (
+ self.lib_dependencies.append(transformer.library)
+ if transformer.library not in self.lib_dependencies
+ else None
+ )
+ return imports
+
+ @classmethod
+ def create_transformer(cls, library: str, fns: list[str]) -> ShikiBaseTransformers:
+ """Create a transformer from a third party library.
+
+ Args:
+ library: The name of the library.
+ fns: The str names of the functions/callables to invoke from the library.
+
+ Returns:
+ A transformer for the specified library.
+
+ Raises:
+ ValueError: If a supplied function name is not valid str.
+ """
+ if any(not isinstance(fn_name, str) for fn_name in fns):
+ raise ValueError(
+ f"the function names should be str names of functions in the specified transformer: {library!r}"
+ )
+ return ShikiBaseTransformers( # type: ignore
+ library=library, fns=[FunctionStringVar.create(fn) for fn in fns]
+ )
+
+ def _render(self, props: dict[str, Any] | None = None):
+ """Renders the component with the given properties, processing transformers if present.
+
+ Args:
+ props: Optional properties to pass to the render function.
+
+ Returns:
+ Rendered component output.
+ """
+ # Ensure props is initialized from class attributes if not provided
+ props = props or {
+ attr.rstrip("_"): getattr(self, attr) for attr in self.get_props()
+ }
+
+ # Extract transformers and apply transformations
+ transformers = props.get("transformers")
+ if transformers is not None:
+ transformed_values = self._process_transformers(transformers._var_value)
+ props["transformers"] = LiteralVar.create(transformed_values)
+
+ return super()._render(props)
+
+ def _process_transformers(self, transformer_list: list) -> list:
+ """Processes a list of transformers, applying transformations where necessary.
+
+ Args:
+ transformer_list: List of transformer objects or values.
+
+ Returns:
+ list: A list of transformed values.
+ """
+ processed = []
+
+ for transformer in transformer_list:
+ if isinstance(transformer, ShikiBaseTransformers):
+ processed.extend(fn.call() for fn in transformer.fns)
+ else:
+ processed.append(transformer)
+
+ return processed
+
+
+class ShikiHighLevelCodeBlock(ShikiCodeBlock):
+ """High level component for the shiki syntax highlighter."""
+
+ # If this is enabled, the default transformers(shikijs transformer) will be used.
+ use_transformers: Var[bool]
+
+ # If this is enabled line numbers will be shown next to the code block.
+ show_line_numbers: Var[bool]
+
+ # Whether a copy button should appear.
+ can_copy: bool = False
+
+ # copy_button: A custom copy button to override the default one.
+ copy_button: Optional[Union[Component, bool]] = None
+
+ @classmethod
+ def create(
+ cls,
+ *children,
+ **props,
+ ) -> Component:
+ """Create a code block component using [shiki syntax highlighter](https://shiki.matsu.io/).
+
+ Args:
+ *children: The children of the component.
+ **props: The props to pass to the component.
+
+ Returns:
+ The code block component.
+ """
+ use_transformers = props.pop("use_transformers", False)
+ show_line_numbers = props.pop("show_line_numbers", False)
+ language = props.pop("language", None)
+ can_copy = props.pop("can_copy", False)
+ copy_button = props.pop("copy_button", None)
+
+ if use_transformers:
+ props["transformers"] = [ShikiJsTransformer()]
+
+ if language is not None:
+ props["language"] = cls._map_languages(language)
+
+ # line numbers are generated via css
+ if show_line_numbers:
+ props["style"] = {**LINE_NUMBER_STYLING, **props.get("style", {})}
+
+ theme = props.pop("theme", None)
+ props["theme"] = props["theme"] = (
+ cls._map_themes(theme)
+ if theme is not None
+ else color_mode_cond( # Default color scheme responds to global color mode.
+ light="one-light",
+ dark="one-dark-pro",
+ )
+ )
+
+ if can_copy:
+ code = children[0]
+ copy_button = ( # type: ignore
+ copy_button
+ if copy_button is not None
+ else Button.create(
+ Icon.create(tag="copy", size=16, color=color("gray", 11)),
+ on_click=[
+ set_clipboard(cls._strip_transformer_triggers(code)), # type: ignore
+ copy_script(),
+ ],
+ style=Style(
+ {
+ "position": "absolute",
+ "top": "4px",
+ "right": "4px",
+ "background": color("gray", 3),
+ "border": "1px solid",
+ "border-color": color("gray", 5),
+ "border-radius": "6px",
+ "padding": "5px",
+ "opacity": "1",
+ "cursor": "pointer",
+ "_hover": {
+ "background": color("gray", 4),
+ },
+ "transition": "background 0.250s ease-out",
+ "&>svg": {
+ "transition": "transform 0.250s ease-out, opacity 0.250s ease-out",
+ },
+ "_active": {
+ "background": color("gray", 5),
+ },
+ }
+ ),
+ )
+ )
+
+ if copy_button:
+ return ShikiCodeBlock.create(
+ children[0], copy_button, position="relative", **props
+ )
+ else:
+ return ShikiCodeBlock.create(children[0], **props)
+
+ @staticmethod
+ def _map_themes(theme: str) -> str:
+ if isinstance(theme, str) and theme in THEME_MAPPING:
+ return THEME_MAPPING[theme]
+ return theme
+
+ @staticmethod
+ def _map_languages(language: str) -> str:
+ if isinstance(language, str) and language in LANGUAGE_MAPPING:
+ return LANGUAGE_MAPPING[language]
+ return language
+
+ @staticmethod
+ def _strip_transformer_triggers(code: str | StringVar) -> StringVar | str:
+ if not isinstance(code, (StringVar, str)):
+ raise VarTypeError(
+ f"code should be string literal or a StringVar type. Got {type(code)} instead."
+ )
+ regex_pattern = r"[\/#]+ *\[!code.*?\]"
+
+ if isinstance(code, Var):
+ return string_replace_operation(
+ code, StringVar(_js_expr=f"/{regex_pattern}/g", _var_type=str), ""
+ )
+ if isinstance(code, str):
+ return re.sub(regex_pattern, "", code)
+
+
+class TransformerNamespace(ComponentNamespace):
+ """Namespace for the Transformers."""
+
+ shikijs = ShikiJsTransformer
+
+
+class CodeblockNamespace(ComponentNamespace):
+ """Namespace for the CodeBlock component."""
+
+ root = staticmethod(ShikiCodeBlock.create)
+ create_transformer = staticmethod(ShikiCodeBlock.create_transformer)
+ transformers = TransformerNamespace()
+ __call__ = staticmethod(ShikiHighLevelCodeBlock.create)
+
+
+code_block = CodeblockNamespace()
diff --git a/reflex/components/datadisplay/shiki_code_block.pyi b/reflex/components/datadisplay/shiki_code_block.pyi
new file mode 100644
index 000000000..e2475aed5
--- /dev/null
+++ b/reflex/components/datadisplay/shiki_code_block.pyi
@@ -0,0 +1,2231 @@
+"""Stub file for reflex/components/datadisplay/shiki_code_block.py"""
+
+# ------------------- DO NOT EDIT ----------------------
+# This file was generated by `reflex/utils/pyi_generator.py`!
+# ------------------------------------------------------
+from typing import Any, Dict, Literal, Optional, Union, overload
+
+from reflex.base import Base
+from reflex.components.component import Component, ComponentNamespace
+from reflex.components.props import NoExtrasAllowedProps
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
+from reflex.vars.function import FunctionStringVar
+
+def copy_script() -> Any: ...
+
+SHIKIJS_TRANSFORMER_FNS = {
+ "transformerNotationDiff",
+ "transformerNotationHighlight",
+ "transformerNotationWordHighlight",
+ "transformerNotationFocus",
+ "transformerNotationErrorLevel",
+ "transformerRenderWhitespace",
+ "transformerMetaHighlight",
+ "transformerMetaWordHighlight",
+ "transformerCompactLineOptions",
+ "transformerRemoveNotationEscape",
+}
+LINE_NUMBER_STYLING = {
+ "code": {
+ "counter-reset": "step",
+ "counter-increment": "step 0",
+ "display": "grid",
+ "line-height": "1.7",
+ "font-size": "0.875em",
+ },
+ "code .line::before": {
+ "content": "counter(step)",
+ "counter-increment": "step",
+ "width": "1rem",
+ "margin-right": "1.5rem",
+ "display": "inline-block",
+ "text-align": "right",
+ "color": "rgba(115,138,148,.4)",
+ },
+}
+BOX_PARENT_STYLING = {
+ "pre": {
+ "margin": "0",
+ "padding": "24px",
+ "background": "transparent",
+ "overflow-x": "auto",
+ "border-radius": "6px",
+ }
+}
+THEME_MAPPING = {
+ "light": "one-light",
+ "dark": "one-dark-pro",
+ "a11y-dark": "github-dark",
+}
+LANGUAGE_MAPPING = {"bash": "shellscript"}
+LiteralCodeLanguage = Literal[
+ "abap",
+ "actionscript-3",
+ "ada",
+ "angular-html",
+ "angular-ts",
+ "apache",
+ "apex",
+ "apl",
+ "applescript",
+ "ara",
+ "asciidoc",
+ "asm",
+ "astro",
+ "awk",
+ "ballerina",
+ "bat",
+ "beancount",
+ "berry",
+ "bibtex",
+ "bicep",
+ "blade",
+ "c",
+ "cadence",
+ "clarity",
+ "clojure",
+ "cmake",
+ "cobol",
+ "codeowners",
+ "codeql",
+ "coffee",
+ "common-lisp",
+ "coq",
+ "cpp",
+ "crystal",
+ "csharp",
+ "css",
+ "csv",
+ "cue",
+ "cypher",
+ "d",
+ "dart",
+ "dax",
+ "desktop",
+ "diff",
+ "docker",
+ "dotenv",
+ "dream-maker",
+ "edge",
+ "elixir",
+ "elm",
+ "emacs-lisp",
+ "erb",
+ "erlang",
+ "fennel",
+ "fish",
+ "fluent",
+ "fortran-fixed-form",
+ "fortran-free-form",
+ "fsharp",
+ "gdresource",
+ "gdscript",
+ "gdshader",
+ "genie",
+ "gherkin",
+ "git-commit",
+ "git-rebase",
+ "gleam",
+ "glimmer-js",
+ "glimmer-ts",
+ "glsl",
+ "gnuplot",
+ "go",
+ "graphql",
+ "groovy",
+ "hack",
+ "haml",
+ "handlebars",
+ "haskell",
+ "haxe",
+ "hcl",
+ "hjson",
+ "hlsl",
+ "html",
+ "html-derivative",
+ "http",
+ "hxml",
+ "hy",
+ "imba",
+ "ini",
+ "java",
+ "javascript",
+ "jinja",
+ "jison",
+ "json",
+ "json5",
+ "jsonc",
+ "jsonl",
+ "jsonnet",
+ "jssm",
+ "jsx",
+ "julia",
+ "kotlin",
+ "kusto",
+ "latex",
+ "lean",
+ "less",
+ "liquid",
+ "log",
+ "logo",
+ "lua",
+ "luau",
+ "make",
+ "markdown",
+ "marko",
+ "matlab",
+ "mdc",
+ "mdx",
+ "mermaid",
+ "mojo",
+ "move",
+ "narrat",
+ "nextflow",
+ "nginx",
+ "nim",
+ "nix",
+ "nushell",
+ "objective-c",
+ "objective-cpp",
+ "ocaml",
+ "pascal",
+ "perl",
+ "php",
+ "plain",
+ "plsql",
+ "po",
+ "postcss",
+ "powerquery",
+ "powershell",
+ "prisma",
+ "prolog",
+ "proto",
+ "pug",
+ "puppet",
+ "purescript",
+ "python",
+ "qml",
+ "qmldir",
+ "qss",
+ "r",
+ "racket",
+ "raku",
+ "razor",
+ "reg",
+ "regexp",
+ "rel",
+ "riscv",
+ "rst",
+ "ruby",
+ "rust",
+ "sas",
+ "sass",
+ "scala",
+ "scheme",
+ "scss",
+ "shaderlab",
+ "shellscript",
+ "shellsession",
+ "smalltalk",
+ "solidity",
+ "soy",
+ "sparql",
+ "splunk",
+ "sql",
+ "ssh-config",
+ "stata",
+ "stylus",
+ "svelte",
+ "swift",
+ "system-verilog",
+ "systemd",
+ "tasl",
+ "tcl",
+ "templ",
+ "terraform",
+ "tex",
+ "toml",
+ "ts-tags",
+ "tsv",
+ "tsx",
+ "turtle",
+ "twig",
+ "typescript",
+ "typespec",
+ "typst",
+ "v",
+ "vala",
+ "vb",
+ "verilog",
+ "vhdl",
+ "viml",
+ "vue",
+ "vue-html",
+ "vyper",
+ "wasm",
+ "wenyan",
+ "wgsl",
+ "wikitext",
+ "wolfram",
+ "xml",
+ "xsl",
+ "yaml",
+ "zenscript",
+ "zig",
+]
+LiteralCodeTheme = Literal[
+ "andromeeda",
+ "aurora-x",
+ "ayu-dark",
+ "catppuccin-frappe",
+ "catppuccin-latte",
+ "catppuccin-macchiato",
+ "catppuccin-mocha",
+ "dark-plus",
+ "dracula",
+ "dracula-soft",
+ "everforest-dark",
+ "everforest-light",
+ "github-dark",
+ "github-dark-default",
+ "github-dark-dimmed",
+ "github-dark-high-contrast",
+ "github-light",
+ "github-light-default",
+ "github-light-high-contrast",
+ "houston",
+ "laserwave",
+ "light-plus",
+ "material-theme",
+ "material-theme-darker",
+ "material-theme-lighter",
+ "material-theme-ocean",
+ "material-theme-palenight",
+ "min-dark",
+ "min-light",
+ "monokai",
+ "night-owl",
+ "nord",
+ "one-dark-pro",
+ "one-light",
+ "plastic",
+ "poimandres",
+ "red",
+ "rose-pine",
+ "rose-pine-dawn",
+ "rose-pine-moon",
+ "slack-dark",
+ "slack-ochin",
+ "snazzy-light",
+ "solarized-dark",
+ "solarized-light",
+ "synthwave-84",
+ "tokyo-night",
+ "vesper",
+ "vitesse-black",
+ "vitesse-dark",
+ "vitesse-light",
+]
+
+class Position(NoExtrasAllowedProps):
+ line: int
+ character: int
+
+class ShikiDecorations(NoExtrasAllowedProps):
+ start: Union[int, Position]
+ end: Union[int, Position]
+ tag_name: str
+ properties: dict[str, Any]
+ always_wrap: bool
+
+class ShikiBaseTransformers(Base):
+ library: str
+ fns: list[FunctionStringVar]
+ style: Optional[Style]
+
+class ShikiJsTransformer(ShikiBaseTransformers):
+ library: str
+ fns: list[FunctionStringVar]
+ style: Optional[Style]
+
+class ShikiCodeBlock(Component):
+ @overload
+ @classmethod
+ def create( # type: ignore
+ cls,
+ *children,
+ language: Optional[
+ Union[
+ Literal[
+ "abap",
+ "actionscript-3",
+ "ada",
+ "angular-html",
+ "angular-ts",
+ "apache",
+ "apex",
+ "apl",
+ "applescript",
+ "ara",
+ "asciidoc",
+ "asm",
+ "astro",
+ "awk",
+ "ballerina",
+ "bat",
+ "beancount",
+ "berry",
+ "bibtex",
+ "bicep",
+ "blade",
+ "c",
+ "cadence",
+ "clarity",
+ "clojure",
+ "cmake",
+ "cobol",
+ "codeowners",
+ "codeql",
+ "coffee",
+ "common-lisp",
+ "coq",
+ "cpp",
+ "crystal",
+ "csharp",
+ "css",
+ "csv",
+ "cue",
+ "cypher",
+ "d",
+ "dart",
+ "dax",
+ "desktop",
+ "diff",
+ "docker",
+ "dotenv",
+ "dream-maker",
+ "edge",
+ "elixir",
+ "elm",
+ "emacs-lisp",
+ "erb",
+ "erlang",
+ "fennel",
+ "fish",
+ "fluent",
+ "fortran-fixed-form",
+ "fortran-free-form",
+ "fsharp",
+ "gdresource",
+ "gdscript",
+ "gdshader",
+ "genie",
+ "gherkin",
+ "git-commit",
+ "git-rebase",
+ "gleam",
+ "glimmer-js",
+ "glimmer-ts",
+ "glsl",
+ "gnuplot",
+ "go",
+ "graphql",
+ "groovy",
+ "hack",
+ "haml",
+ "handlebars",
+ "haskell",
+ "haxe",
+ "hcl",
+ "hjson",
+ "hlsl",
+ "html",
+ "html-derivative",
+ "http",
+ "hxml",
+ "hy",
+ "imba",
+ "ini",
+ "java",
+ "javascript",
+ "jinja",
+ "jison",
+ "json",
+ "json5",
+ "jsonc",
+ "jsonl",
+ "jsonnet",
+ "jssm",
+ "jsx",
+ "julia",
+ "kotlin",
+ "kusto",
+ "latex",
+ "lean",
+ "less",
+ "liquid",
+ "log",
+ "logo",
+ "lua",
+ "luau",
+ "make",
+ "markdown",
+ "marko",
+ "matlab",
+ "mdc",
+ "mdx",
+ "mermaid",
+ "mojo",
+ "move",
+ "narrat",
+ "nextflow",
+ "nginx",
+ "nim",
+ "nix",
+ "nushell",
+ "objective-c",
+ "objective-cpp",
+ "ocaml",
+ "pascal",
+ "perl",
+ "php",
+ "plain",
+ "plsql",
+ "po",
+ "postcss",
+ "powerquery",
+ "powershell",
+ "prisma",
+ "prolog",
+ "proto",
+ "pug",
+ "puppet",
+ "purescript",
+ "python",
+ "qml",
+ "qmldir",
+ "qss",
+ "r",
+ "racket",
+ "raku",
+ "razor",
+ "reg",
+ "regexp",
+ "rel",
+ "riscv",
+ "rst",
+ "ruby",
+ "rust",
+ "sas",
+ "sass",
+ "scala",
+ "scheme",
+ "scss",
+ "shaderlab",
+ "shellscript",
+ "shellsession",
+ "smalltalk",
+ "solidity",
+ "soy",
+ "sparql",
+ "splunk",
+ "sql",
+ "ssh-config",
+ "stata",
+ "stylus",
+ "svelte",
+ "swift",
+ "system-verilog",
+ "systemd",
+ "tasl",
+ "tcl",
+ "templ",
+ "terraform",
+ "tex",
+ "toml",
+ "ts-tags",
+ "tsv",
+ "tsx",
+ "turtle",
+ "twig",
+ "typescript",
+ "typespec",
+ "typst",
+ "v",
+ "vala",
+ "vb",
+ "verilog",
+ "vhdl",
+ "viml",
+ "vue",
+ "vue-html",
+ "vyper",
+ "wasm",
+ "wenyan",
+ "wgsl",
+ "wikitext",
+ "wolfram",
+ "xml",
+ "xsl",
+ "yaml",
+ "zenscript",
+ "zig",
+ ],
+ Var[
+ Literal[
+ "abap",
+ "actionscript-3",
+ "ada",
+ "angular-html",
+ "angular-ts",
+ "apache",
+ "apex",
+ "apl",
+ "applescript",
+ "ara",
+ "asciidoc",
+ "asm",
+ "astro",
+ "awk",
+ "ballerina",
+ "bat",
+ "beancount",
+ "berry",
+ "bibtex",
+ "bicep",
+ "blade",
+ "c",
+ "cadence",
+ "clarity",
+ "clojure",
+ "cmake",
+ "cobol",
+ "codeowners",
+ "codeql",
+ "coffee",
+ "common-lisp",
+ "coq",
+ "cpp",
+ "crystal",
+ "csharp",
+ "css",
+ "csv",
+ "cue",
+ "cypher",
+ "d",
+ "dart",
+ "dax",
+ "desktop",
+ "diff",
+ "docker",
+ "dotenv",
+ "dream-maker",
+ "edge",
+ "elixir",
+ "elm",
+ "emacs-lisp",
+ "erb",
+ "erlang",
+ "fennel",
+ "fish",
+ "fluent",
+ "fortran-fixed-form",
+ "fortran-free-form",
+ "fsharp",
+ "gdresource",
+ "gdscript",
+ "gdshader",
+ "genie",
+ "gherkin",
+ "git-commit",
+ "git-rebase",
+ "gleam",
+ "glimmer-js",
+ "glimmer-ts",
+ "glsl",
+ "gnuplot",
+ "go",
+ "graphql",
+ "groovy",
+ "hack",
+ "haml",
+ "handlebars",
+ "haskell",
+ "haxe",
+ "hcl",
+ "hjson",
+ "hlsl",
+ "html",
+ "html-derivative",
+ "http",
+ "hxml",
+ "hy",
+ "imba",
+ "ini",
+ "java",
+ "javascript",
+ "jinja",
+ "jison",
+ "json",
+ "json5",
+ "jsonc",
+ "jsonl",
+ "jsonnet",
+ "jssm",
+ "jsx",
+ "julia",
+ "kotlin",
+ "kusto",
+ "latex",
+ "lean",
+ "less",
+ "liquid",
+ "log",
+ "logo",
+ "lua",
+ "luau",
+ "make",
+ "markdown",
+ "marko",
+ "matlab",
+ "mdc",
+ "mdx",
+ "mermaid",
+ "mojo",
+ "move",
+ "narrat",
+ "nextflow",
+ "nginx",
+ "nim",
+ "nix",
+ "nushell",
+ "objective-c",
+ "objective-cpp",
+ "ocaml",
+ "pascal",
+ "perl",
+ "php",
+ "plain",
+ "plsql",
+ "po",
+ "postcss",
+ "powerquery",
+ "powershell",
+ "prisma",
+ "prolog",
+ "proto",
+ "pug",
+ "puppet",
+ "purescript",
+ "python",
+ "qml",
+ "qmldir",
+ "qss",
+ "r",
+ "racket",
+ "raku",
+ "razor",
+ "reg",
+ "regexp",
+ "rel",
+ "riscv",
+ "rst",
+ "ruby",
+ "rust",
+ "sas",
+ "sass",
+ "scala",
+ "scheme",
+ "scss",
+ "shaderlab",
+ "shellscript",
+ "shellsession",
+ "smalltalk",
+ "solidity",
+ "soy",
+ "sparql",
+ "splunk",
+ "sql",
+ "ssh-config",
+ "stata",
+ "stylus",
+ "svelte",
+ "swift",
+ "system-verilog",
+ "systemd",
+ "tasl",
+ "tcl",
+ "templ",
+ "terraform",
+ "tex",
+ "toml",
+ "ts-tags",
+ "tsv",
+ "tsx",
+ "turtle",
+ "twig",
+ "typescript",
+ "typespec",
+ "typst",
+ "v",
+ "vala",
+ "vb",
+ "verilog",
+ "vhdl",
+ "viml",
+ "vue",
+ "vue-html",
+ "vyper",
+ "wasm",
+ "wenyan",
+ "wgsl",
+ "wikitext",
+ "wolfram",
+ "xml",
+ "xsl",
+ "yaml",
+ "zenscript",
+ "zig",
+ ]
+ ],
+ ]
+ ] = None,
+ theme: Optional[
+ Union[
+ Literal[
+ "andromeeda",
+ "aurora-x",
+ "ayu-dark",
+ "catppuccin-frappe",
+ "catppuccin-latte",
+ "catppuccin-macchiato",
+ "catppuccin-mocha",
+ "dark-plus",
+ "dracula",
+ "dracula-soft",
+ "everforest-dark",
+ "everforest-light",
+ "github-dark",
+ "github-dark-default",
+ "github-dark-dimmed",
+ "github-dark-high-contrast",
+ "github-light",
+ "github-light-default",
+ "github-light-high-contrast",
+ "houston",
+ "laserwave",
+ "light-plus",
+ "material-theme",
+ "material-theme-darker",
+ "material-theme-lighter",
+ "material-theme-ocean",
+ "material-theme-palenight",
+ "min-dark",
+ "min-light",
+ "monokai",
+ "night-owl",
+ "nord",
+ "one-dark-pro",
+ "one-light",
+ "plastic",
+ "poimandres",
+ "red",
+ "rose-pine",
+ "rose-pine-dawn",
+ "rose-pine-moon",
+ "slack-dark",
+ "slack-ochin",
+ "snazzy-light",
+ "solarized-dark",
+ "solarized-light",
+ "synthwave-84",
+ "tokyo-night",
+ "vesper",
+ "vitesse-black",
+ "vitesse-dark",
+ "vitesse-light",
+ ],
+ Var[
+ Literal[
+ "andromeeda",
+ "aurora-x",
+ "ayu-dark",
+ "catppuccin-frappe",
+ "catppuccin-latte",
+ "catppuccin-macchiato",
+ "catppuccin-mocha",
+ "dark-plus",
+ "dracula",
+ "dracula-soft",
+ "everforest-dark",
+ "everforest-light",
+ "github-dark",
+ "github-dark-default",
+ "github-dark-dimmed",
+ "github-dark-high-contrast",
+ "github-light",
+ "github-light-default",
+ "github-light-high-contrast",
+ "houston",
+ "laserwave",
+ "light-plus",
+ "material-theme",
+ "material-theme-darker",
+ "material-theme-lighter",
+ "material-theme-ocean",
+ "material-theme-palenight",
+ "min-dark",
+ "min-light",
+ "monokai",
+ "night-owl",
+ "nord",
+ "one-dark-pro",
+ "one-light",
+ "plastic",
+ "poimandres",
+ "red",
+ "rose-pine",
+ "rose-pine-dawn",
+ "rose-pine-moon",
+ "slack-dark",
+ "slack-ochin",
+ "snazzy-light",
+ "solarized-dark",
+ "solarized-light",
+ "synthwave-84",
+ "tokyo-night",
+ "vesper",
+ "vitesse-black",
+ "vitesse-dark",
+ "vitesse-light",
+ ]
+ ],
+ ]
+ ] = None,
+ themes: Optional[
+ Union[
+ Var[Union[dict[str, str], list[dict[str, Any]]]],
+ dict[str, str],
+ list[dict[str, Any]],
+ ]
+ ] = None,
+ code: Optional[Union[Var[str], str]] = None,
+ transformers: Optional[
+ Union[
+ Var[list[Union[ShikiBaseTransformers, dict[str, Any]]]],
+ list[Union[ShikiBaseTransformers, dict[str, Any]]],
+ ]
+ ] = None,
+ decorations: Optional[
+ Union[Var[list[ShikiDecorations]], list[ShikiDecorations]]
+ ] = None,
+ style: Optional[Style] = None,
+ key: Optional[Any] = None,
+ id: Optional[Any] = None,
+ class_name: Optional[Any] = None,
+ autofocus: Optional[bool] = None,
+ custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
+ ) -> "ShikiCodeBlock":
+ """Create a code block component using [shiki syntax highlighter](https://shiki.matsu.io/).
+
+ Args:
+ *children: The children of the component.
+ language: The language to use.
+ theme: The theme to use ("light" or "dark").
+ themes: The set of themes to use for different modes.
+ code: The code to display.
+ transformers: The transformers to use for the syntax highlighter.
+ decorations: The decorations to use for the syntax highlighter.
+ style: The style of the component.
+ key: A unique key for the component.
+ id: The id for the component.
+ class_name: The class name for the component.
+ autofocus: Whether the component should take the focus once the page is loaded
+ custom_attrs: custom attribute
+ **props: The props to pass to the component.
+
+ Returns:
+ The code block component.
+ """
+ ...
+
+ def add_imports(self) -> dict[str, list[str]]: ...
+ @classmethod
+ def create_transformer(
+ cls, library: str, fns: list[str]
+ ) -> ShikiBaseTransformers: ...
+
+class ShikiHighLevelCodeBlock(ShikiCodeBlock):
+ @overload
+ @classmethod
+ def create( # type: ignore
+ cls,
+ *children,
+ use_transformers: Optional[Union[Var[bool], bool]] = None,
+ show_line_numbers: Optional[Union[Var[bool], bool]] = None,
+ can_copy: Optional[bool] = None,
+ copy_button: Optional[Union[Component, bool]] = None,
+ language: Optional[
+ Union[
+ Literal[
+ "abap",
+ "actionscript-3",
+ "ada",
+ "angular-html",
+ "angular-ts",
+ "apache",
+ "apex",
+ "apl",
+ "applescript",
+ "ara",
+ "asciidoc",
+ "asm",
+ "astro",
+ "awk",
+ "ballerina",
+ "bat",
+ "beancount",
+ "berry",
+ "bibtex",
+ "bicep",
+ "blade",
+ "c",
+ "cadence",
+ "clarity",
+ "clojure",
+ "cmake",
+ "cobol",
+ "codeowners",
+ "codeql",
+ "coffee",
+ "common-lisp",
+ "coq",
+ "cpp",
+ "crystal",
+ "csharp",
+ "css",
+ "csv",
+ "cue",
+ "cypher",
+ "d",
+ "dart",
+ "dax",
+ "desktop",
+ "diff",
+ "docker",
+ "dotenv",
+ "dream-maker",
+ "edge",
+ "elixir",
+ "elm",
+ "emacs-lisp",
+ "erb",
+ "erlang",
+ "fennel",
+ "fish",
+ "fluent",
+ "fortran-fixed-form",
+ "fortran-free-form",
+ "fsharp",
+ "gdresource",
+ "gdscript",
+ "gdshader",
+ "genie",
+ "gherkin",
+ "git-commit",
+ "git-rebase",
+ "gleam",
+ "glimmer-js",
+ "glimmer-ts",
+ "glsl",
+ "gnuplot",
+ "go",
+ "graphql",
+ "groovy",
+ "hack",
+ "haml",
+ "handlebars",
+ "haskell",
+ "haxe",
+ "hcl",
+ "hjson",
+ "hlsl",
+ "html",
+ "html-derivative",
+ "http",
+ "hxml",
+ "hy",
+ "imba",
+ "ini",
+ "java",
+ "javascript",
+ "jinja",
+ "jison",
+ "json",
+ "json5",
+ "jsonc",
+ "jsonl",
+ "jsonnet",
+ "jssm",
+ "jsx",
+ "julia",
+ "kotlin",
+ "kusto",
+ "latex",
+ "lean",
+ "less",
+ "liquid",
+ "log",
+ "logo",
+ "lua",
+ "luau",
+ "make",
+ "markdown",
+ "marko",
+ "matlab",
+ "mdc",
+ "mdx",
+ "mermaid",
+ "mojo",
+ "move",
+ "narrat",
+ "nextflow",
+ "nginx",
+ "nim",
+ "nix",
+ "nushell",
+ "objective-c",
+ "objective-cpp",
+ "ocaml",
+ "pascal",
+ "perl",
+ "php",
+ "plain",
+ "plsql",
+ "po",
+ "postcss",
+ "powerquery",
+ "powershell",
+ "prisma",
+ "prolog",
+ "proto",
+ "pug",
+ "puppet",
+ "purescript",
+ "python",
+ "qml",
+ "qmldir",
+ "qss",
+ "r",
+ "racket",
+ "raku",
+ "razor",
+ "reg",
+ "regexp",
+ "rel",
+ "riscv",
+ "rst",
+ "ruby",
+ "rust",
+ "sas",
+ "sass",
+ "scala",
+ "scheme",
+ "scss",
+ "shaderlab",
+ "shellscript",
+ "shellsession",
+ "smalltalk",
+ "solidity",
+ "soy",
+ "sparql",
+ "splunk",
+ "sql",
+ "ssh-config",
+ "stata",
+ "stylus",
+ "svelte",
+ "swift",
+ "system-verilog",
+ "systemd",
+ "tasl",
+ "tcl",
+ "templ",
+ "terraform",
+ "tex",
+ "toml",
+ "ts-tags",
+ "tsv",
+ "tsx",
+ "turtle",
+ "twig",
+ "typescript",
+ "typespec",
+ "typst",
+ "v",
+ "vala",
+ "vb",
+ "verilog",
+ "vhdl",
+ "viml",
+ "vue",
+ "vue-html",
+ "vyper",
+ "wasm",
+ "wenyan",
+ "wgsl",
+ "wikitext",
+ "wolfram",
+ "xml",
+ "xsl",
+ "yaml",
+ "zenscript",
+ "zig",
+ ],
+ Var[
+ Literal[
+ "abap",
+ "actionscript-3",
+ "ada",
+ "angular-html",
+ "angular-ts",
+ "apache",
+ "apex",
+ "apl",
+ "applescript",
+ "ara",
+ "asciidoc",
+ "asm",
+ "astro",
+ "awk",
+ "ballerina",
+ "bat",
+ "beancount",
+ "berry",
+ "bibtex",
+ "bicep",
+ "blade",
+ "c",
+ "cadence",
+ "clarity",
+ "clojure",
+ "cmake",
+ "cobol",
+ "codeowners",
+ "codeql",
+ "coffee",
+ "common-lisp",
+ "coq",
+ "cpp",
+ "crystal",
+ "csharp",
+ "css",
+ "csv",
+ "cue",
+ "cypher",
+ "d",
+ "dart",
+ "dax",
+ "desktop",
+ "diff",
+ "docker",
+ "dotenv",
+ "dream-maker",
+ "edge",
+ "elixir",
+ "elm",
+ "emacs-lisp",
+ "erb",
+ "erlang",
+ "fennel",
+ "fish",
+ "fluent",
+ "fortran-fixed-form",
+ "fortran-free-form",
+ "fsharp",
+ "gdresource",
+ "gdscript",
+ "gdshader",
+ "genie",
+ "gherkin",
+ "git-commit",
+ "git-rebase",
+ "gleam",
+ "glimmer-js",
+ "glimmer-ts",
+ "glsl",
+ "gnuplot",
+ "go",
+ "graphql",
+ "groovy",
+ "hack",
+ "haml",
+ "handlebars",
+ "haskell",
+ "haxe",
+ "hcl",
+ "hjson",
+ "hlsl",
+ "html",
+ "html-derivative",
+ "http",
+ "hxml",
+ "hy",
+ "imba",
+ "ini",
+ "java",
+ "javascript",
+ "jinja",
+ "jison",
+ "json",
+ "json5",
+ "jsonc",
+ "jsonl",
+ "jsonnet",
+ "jssm",
+ "jsx",
+ "julia",
+ "kotlin",
+ "kusto",
+ "latex",
+ "lean",
+ "less",
+ "liquid",
+ "log",
+ "logo",
+ "lua",
+ "luau",
+ "make",
+ "markdown",
+ "marko",
+ "matlab",
+ "mdc",
+ "mdx",
+ "mermaid",
+ "mojo",
+ "move",
+ "narrat",
+ "nextflow",
+ "nginx",
+ "nim",
+ "nix",
+ "nushell",
+ "objective-c",
+ "objective-cpp",
+ "ocaml",
+ "pascal",
+ "perl",
+ "php",
+ "plain",
+ "plsql",
+ "po",
+ "postcss",
+ "powerquery",
+ "powershell",
+ "prisma",
+ "prolog",
+ "proto",
+ "pug",
+ "puppet",
+ "purescript",
+ "python",
+ "qml",
+ "qmldir",
+ "qss",
+ "r",
+ "racket",
+ "raku",
+ "razor",
+ "reg",
+ "regexp",
+ "rel",
+ "riscv",
+ "rst",
+ "ruby",
+ "rust",
+ "sas",
+ "sass",
+ "scala",
+ "scheme",
+ "scss",
+ "shaderlab",
+ "shellscript",
+ "shellsession",
+ "smalltalk",
+ "solidity",
+ "soy",
+ "sparql",
+ "splunk",
+ "sql",
+ "ssh-config",
+ "stata",
+ "stylus",
+ "svelte",
+ "swift",
+ "system-verilog",
+ "systemd",
+ "tasl",
+ "tcl",
+ "templ",
+ "terraform",
+ "tex",
+ "toml",
+ "ts-tags",
+ "tsv",
+ "tsx",
+ "turtle",
+ "twig",
+ "typescript",
+ "typespec",
+ "typst",
+ "v",
+ "vala",
+ "vb",
+ "verilog",
+ "vhdl",
+ "viml",
+ "vue",
+ "vue-html",
+ "vyper",
+ "wasm",
+ "wenyan",
+ "wgsl",
+ "wikitext",
+ "wolfram",
+ "xml",
+ "xsl",
+ "yaml",
+ "zenscript",
+ "zig",
+ ]
+ ],
+ ]
+ ] = None,
+ theme: Optional[
+ Union[
+ Literal[
+ "andromeeda",
+ "aurora-x",
+ "ayu-dark",
+ "catppuccin-frappe",
+ "catppuccin-latte",
+ "catppuccin-macchiato",
+ "catppuccin-mocha",
+ "dark-plus",
+ "dracula",
+ "dracula-soft",
+ "everforest-dark",
+ "everforest-light",
+ "github-dark",
+ "github-dark-default",
+ "github-dark-dimmed",
+ "github-dark-high-contrast",
+ "github-light",
+ "github-light-default",
+ "github-light-high-contrast",
+ "houston",
+ "laserwave",
+ "light-plus",
+ "material-theme",
+ "material-theme-darker",
+ "material-theme-lighter",
+ "material-theme-ocean",
+ "material-theme-palenight",
+ "min-dark",
+ "min-light",
+ "monokai",
+ "night-owl",
+ "nord",
+ "one-dark-pro",
+ "one-light",
+ "plastic",
+ "poimandres",
+ "red",
+ "rose-pine",
+ "rose-pine-dawn",
+ "rose-pine-moon",
+ "slack-dark",
+ "slack-ochin",
+ "snazzy-light",
+ "solarized-dark",
+ "solarized-light",
+ "synthwave-84",
+ "tokyo-night",
+ "vesper",
+ "vitesse-black",
+ "vitesse-dark",
+ "vitesse-light",
+ ],
+ Var[
+ Literal[
+ "andromeeda",
+ "aurora-x",
+ "ayu-dark",
+ "catppuccin-frappe",
+ "catppuccin-latte",
+ "catppuccin-macchiato",
+ "catppuccin-mocha",
+ "dark-plus",
+ "dracula",
+ "dracula-soft",
+ "everforest-dark",
+ "everforest-light",
+ "github-dark",
+ "github-dark-default",
+ "github-dark-dimmed",
+ "github-dark-high-contrast",
+ "github-light",
+ "github-light-default",
+ "github-light-high-contrast",
+ "houston",
+ "laserwave",
+ "light-plus",
+ "material-theme",
+ "material-theme-darker",
+ "material-theme-lighter",
+ "material-theme-ocean",
+ "material-theme-palenight",
+ "min-dark",
+ "min-light",
+ "monokai",
+ "night-owl",
+ "nord",
+ "one-dark-pro",
+ "one-light",
+ "plastic",
+ "poimandres",
+ "red",
+ "rose-pine",
+ "rose-pine-dawn",
+ "rose-pine-moon",
+ "slack-dark",
+ "slack-ochin",
+ "snazzy-light",
+ "solarized-dark",
+ "solarized-light",
+ "synthwave-84",
+ "tokyo-night",
+ "vesper",
+ "vitesse-black",
+ "vitesse-dark",
+ "vitesse-light",
+ ]
+ ],
+ ]
+ ] = None,
+ themes: Optional[
+ Union[
+ Var[Union[dict[str, str], list[dict[str, Any]]]],
+ dict[str, str],
+ list[dict[str, Any]],
+ ]
+ ] = None,
+ code: Optional[Union[Var[str], str]] = None,
+ transformers: Optional[
+ Union[
+ Var[list[Union[ShikiBaseTransformers, dict[str, Any]]]],
+ list[Union[ShikiBaseTransformers, dict[str, Any]]],
+ ]
+ ] = None,
+ decorations: Optional[
+ Union[Var[list[ShikiDecorations]], list[ShikiDecorations]]
+ ] = None,
+ style: Optional[Style] = None,
+ key: Optional[Any] = None,
+ id: Optional[Any] = None,
+ class_name: Optional[Any] = None,
+ autofocus: Optional[bool] = None,
+ custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
+ ) -> "ShikiHighLevelCodeBlock":
+ """Create a code block component using [shiki syntax highlighter](https://shiki.matsu.io/).
+
+ Args:
+ *children: The children of the component.
+ use_transformers: If this is enabled, the default transformers(shikijs transformer) will be used.
+ show_line_numbers: If this is enabled line numbers will be shown next to the code block.
+ can_copy: Whether a copy button should appear.
+ copy_button: copy_button: A custom copy button to override the default one.
+ language: The language to use.
+ theme: The theme to use ("light" or "dark").
+ themes: The set of themes to use for different modes.
+ code: The code to display.
+ transformers: The transformers to use for the syntax highlighter.
+ decorations: The decorations to use for the syntax highlighter.
+ style: The style of the component.
+ key: A unique key for the component.
+ id: The id for the component.
+ class_name: The class name for the component.
+ autofocus: Whether the component should take the focus once the page is loaded
+ custom_attrs: custom attribute
+ **props: The props to pass to the component.
+
+ Returns:
+ The code block component.
+ """
+ ...
+
+class TransformerNamespace(ComponentNamespace):
+ shikijs = ShikiJsTransformer
+
+class CodeblockNamespace(ComponentNamespace):
+ root = staticmethod(ShikiCodeBlock.create)
+ create_transformer = staticmethod(ShikiCodeBlock.create_transformer)
+ transformers = TransformerNamespace()
+
+ @staticmethod
+ def __call__(
+ *children,
+ use_transformers: Optional[Union[Var[bool], bool]] = None,
+ show_line_numbers: Optional[Union[Var[bool], bool]] = None,
+ can_copy: Optional[bool] = None,
+ copy_button: Optional[Union[Component, bool]] = None,
+ language: Optional[
+ Union[
+ Literal[
+ "abap",
+ "actionscript-3",
+ "ada",
+ "angular-html",
+ "angular-ts",
+ "apache",
+ "apex",
+ "apl",
+ "applescript",
+ "ara",
+ "asciidoc",
+ "asm",
+ "astro",
+ "awk",
+ "ballerina",
+ "bat",
+ "beancount",
+ "berry",
+ "bibtex",
+ "bicep",
+ "blade",
+ "c",
+ "cadence",
+ "clarity",
+ "clojure",
+ "cmake",
+ "cobol",
+ "codeowners",
+ "codeql",
+ "coffee",
+ "common-lisp",
+ "coq",
+ "cpp",
+ "crystal",
+ "csharp",
+ "css",
+ "csv",
+ "cue",
+ "cypher",
+ "d",
+ "dart",
+ "dax",
+ "desktop",
+ "diff",
+ "docker",
+ "dotenv",
+ "dream-maker",
+ "edge",
+ "elixir",
+ "elm",
+ "emacs-lisp",
+ "erb",
+ "erlang",
+ "fennel",
+ "fish",
+ "fluent",
+ "fortran-fixed-form",
+ "fortran-free-form",
+ "fsharp",
+ "gdresource",
+ "gdscript",
+ "gdshader",
+ "genie",
+ "gherkin",
+ "git-commit",
+ "git-rebase",
+ "gleam",
+ "glimmer-js",
+ "glimmer-ts",
+ "glsl",
+ "gnuplot",
+ "go",
+ "graphql",
+ "groovy",
+ "hack",
+ "haml",
+ "handlebars",
+ "haskell",
+ "haxe",
+ "hcl",
+ "hjson",
+ "hlsl",
+ "html",
+ "html-derivative",
+ "http",
+ "hxml",
+ "hy",
+ "imba",
+ "ini",
+ "java",
+ "javascript",
+ "jinja",
+ "jison",
+ "json",
+ "json5",
+ "jsonc",
+ "jsonl",
+ "jsonnet",
+ "jssm",
+ "jsx",
+ "julia",
+ "kotlin",
+ "kusto",
+ "latex",
+ "lean",
+ "less",
+ "liquid",
+ "log",
+ "logo",
+ "lua",
+ "luau",
+ "make",
+ "markdown",
+ "marko",
+ "matlab",
+ "mdc",
+ "mdx",
+ "mermaid",
+ "mojo",
+ "move",
+ "narrat",
+ "nextflow",
+ "nginx",
+ "nim",
+ "nix",
+ "nushell",
+ "objective-c",
+ "objective-cpp",
+ "ocaml",
+ "pascal",
+ "perl",
+ "php",
+ "plain",
+ "plsql",
+ "po",
+ "postcss",
+ "powerquery",
+ "powershell",
+ "prisma",
+ "prolog",
+ "proto",
+ "pug",
+ "puppet",
+ "purescript",
+ "python",
+ "qml",
+ "qmldir",
+ "qss",
+ "r",
+ "racket",
+ "raku",
+ "razor",
+ "reg",
+ "regexp",
+ "rel",
+ "riscv",
+ "rst",
+ "ruby",
+ "rust",
+ "sas",
+ "sass",
+ "scala",
+ "scheme",
+ "scss",
+ "shaderlab",
+ "shellscript",
+ "shellsession",
+ "smalltalk",
+ "solidity",
+ "soy",
+ "sparql",
+ "splunk",
+ "sql",
+ "ssh-config",
+ "stata",
+ "stylus",
+ "svelte",
+ "swift",
+ "system-verilog",
+ "systemd",
+ "tasl",
+ "tcl",
+ "templ",
+ "terraform",
+ "tex",
+ "toml",
+ "ts-tags",
+ "tsv",
+ "tsx",
+ "turtle",
+ "twig",
+ "typescript",
+ "typespec",
+ "typst",
+ "v",
+ "vala",
+ "vb",
+ "verilog",
+ "vhdl",
+ "viml",
+ "vue",
+ "vue-html",
+ "vyper",
+ "wasm",
+ "wenyan",
+ "wgsl",
+ "wikitext",
+ "wolfram",
+ "xml",
+ "xsl",
+ "yaml",
+ "zenscript",
+ "zig",
+ ],
+ Var[
+ Literal[
+ "abap",
+ "actionscript-3",
+ "ada",
+ "angular-html",
+ "angular-ts",
+ "apache",
+ "apex",
+ "apl",
+ "applescript",
+ "ara",
+ "asciidoc",
+ "asm",
+ "astro",
+ "awk",
+ "ballerina",
+ "bat",
+ "beancount",
+ "berry",
+ "bibtex",
+ "bicep",
+ "blade",
+ "c",
+ "cadence",
+ "clarity",
+ "clojure",
+ "cmake",
+ "cobol",
+ "codeowners",
+ "codeql",
+ "coffee",
+ "common-lisp",
+ "coq",
+ "cpp",
+ "crystal",
+ "csharp",
+ "css",
+ "csv",
+ "cue",
+ "cypher",
+ "d",
+ "dart",
+ "dax",
+ "desktop",
+ "diff",
+ "docker",
+ "dotenv",
+ "dream-maker",
+ "edge",
+ "elixir",
+ "elm",
+ "emacs-lisp",
+ "erb",
+ "erlang",
+ "fennel",
+ "fish",
+ "fluent",
+ "fortran-fixed-form",
+ "fortran-free-form",
+ "fsharp",
+ "gdresource",
+ "gdscript",
+ "gdshader",
+ "genie",
+ "gherkin",
+ "git-commit",
+ "git-rebase",
+ "gleam",
+ "glimmer-js",
+ "glimmer-ts",
+ "glsl",
+ "gnuplot",
+ "go",
+ "graphql",
+ "groovy",
+ "hack",
+ "haml",
+ "handlebars",
+ "haskell",
+ "haxe",
+ "hcl",
+ "hjson",
+ "hlsl",
+ "html",
+ "html-derivative",
+ "http",
+ "hxml",
+ "hy",
+ "imba",
+ "ini",
+ "java",
+ "javascript",
+ "jinja",
+ "jison",
+ "json",
+ "json5",
+ "jsonc",
+ "jsonl",
+ "jsonnet",
+ "jssm",
+ "jsx",
+ "julia",
+ "kotlin",
+ "kusto",
+ "latex",
+ "lean",
+ "less",
+ "liquid",
+ "log",
+ "logo",
+ "lua",
+ "luau",
+ "make",
+ "markdown",
+ "marko",
+ "matlab",
+ "mdc",
+ "mdx",
+ "mermaid",
+ "mojo",
+ "move",
+ "narrat",
+ "nextflow",
+ "nginx",
+ "nim",
+ "nix",
+ "nushell",
+ "objective-c",
+ "objective-cpp",
+ "ocaml",
+ "pascal",
+ "perl",
+ "php",
+ "plain",
+ "plsql",
+ "po",
+ "postcss",
+ "powerquery",
+ "powershell",
+ "prisma",
+ "prolog",
+ "proto",
+ "pug",
+ "puppet",
+ "purescript",
+ "python",
+ "qml",
+ "qmldir",
+ "qss",
+ "r",
+ "racket",
+ "raku",
+ "razor",
+ "reg",
+ "regexp",
+ "rel",
+ "riscv",
+ "rst",
+ "ruby",
+ "rust",
+ "sas",
+ "sass",
+ "scala",
+ "scheme",
+ "scss",
+ "shaderlab",
+ "shellscript",
+ "shellsession",
+ "smalltalk",
+ "solidity",
+ "soy",
+ "sparql",
+ "splunk",
+ "sql",
+ "ssh-config",
+ "stata",
+ "stylus",
+ "svelte",
+ "swift",
+ "system-verilog",
+ "systemd",
+ "tasl",
+ "tcl",
+ "templ",
+ "terraform",
+ "tex",
+ "toml",
+ "ts-tags",
+ "tsv",
+ "tsx",
+ "turtle",
+ "twig",
+ "typescript",
+ "typespec",
+ "typst",
+ "v",
+ "vala",
+ "vb",
+ "verilog",
+ "vhdl",
+ "viml",
+ "vue",
+ "vue-html",
+ "vyper",
+ "wasm",
+ "wenyan",
+ "wgsl",
+ "wikitext",
+ "wolfram",
+ "xml",
+ "xsl",
+ "yaml",
+ "zenscript",
+ "zig",
+ ]
+ ],
+ ]
+ ] = None,
+ theme: Optional[
+ Union[
+ Literal[
+ "andromeeda",
+ "aurora-x",
+ "ayu-dark",
+ "catppuccin-frappe",
+ "catppuccin-latte",
+ "catppuccin-macchiato",
+ "catppuccin-mocha",
+ "dark-plus",
+ "dracula",
+ "dracula-soft",
+ "everforest-dark",
+ "everforest-light",
+ "github-dark",
+ "github-dark-default",
+ "github-dark-dimmed",
+ "github-dark-high-contrast",
+ "github-light",
+ "github-light-default",
+ "github-light-high-contrast",
+ "houston",
+ "laserwave",
+ "light-plus",
+ "material-theme",
+ "material-theme-darker",
+ "material-theme-lighter",
+ "material-theme-ocean",
+ "material-theme-palenight",
+ "min-dark",
+ "min-light",
+ "monokai",
+ "night-owl",
+ "nord",
+ "one-dark-pro",
+ "one-light",
+ "plastic",
+ "poimandres",
+ "red",
+ "rose-pine",
+ "rose-pine-dawn",
+ "rose-pine-moon",
+ "slack-dark",
+ "slack-ochin",
+ "snazzy-light",
+ "solarized-dark",
+ "solarized-light",
+ "synthwave-84",
+ "tokyo-night",
+ "vesper",
+ "vitesse-black",
+ "vitesse-dark",
+ "vitesse-light",
+ ],
+ Var[
+ Literal[
+ "andromeeda",
+ "aurora-x",
+ "ayu-dark",
+ "catppuccin-frappe",
+ "catppuccin-latte",
+ "catppuccin-macchiato",
+ "catppuccin-mocha",
+ "dark-plus",
+ "dracula",
+ "dracula-soft",
+ "everforest-dark",
+ "everforest-light",
+ "github-dark",
+ "github-dark-default",
+ "github-dark-dimmed",
+ "github-dark-high-contrast",
+ "github-light",
+ "github-light-default",
+ "github-light-high-contrast",
+ "houston",
+ "laserwave",
+ "light-plus",
+ "material-theme",
+ "material-theme-darker",
+ "material-theme-lighter",
+ "material-theme-ocean",
+ "material-theme-palenight",
+ "min-dark",
+ "min-light",
+ "monokai",
+ "night-owl",
+ "nord",
+ "one-dark-pro",
+ "one-light",
+ "plastic",
+ "poimandres",
+ "red",
+ "rose-pine",
+ "rose-pine-dawn",
+ "rose-pine-moon",
+ "slack-dark",
+ "slack-ochin",
+ "snazzy-light",
+ "solarized-dark",
+ "solarized-light",
+ "synthwave-84",
+ "tokyo-night",
+ "vesper",
+ "vitesse-black",
+ "vitesse-dark",
+ "vitesse-light",
+ ]
+ ],
+ ]
+ ] = None,
+ themes: Optional[
+ Union[
+ Var[Union[dict[str, str], list[dict[str, Any]]]],
+ dict[str, str],
+ list[dict[str, Any]],
+ ]
+ ] = None,
+ code: Optional[Union[Var[str], str]] = None,
+ transformers: Optional[
+ Union[
+ Var[list[Union[ShikiBaseTransformers, dict[str, Any]]]],
+ list[Union[ShikiBaseTransformers, dict[str, Any]]],
+ ]
+ ] = None,
+ decorations: Optional[
+ Union[Var[list[ShikiDecorations]], list[ShikiDecorations]]
+ ] = None,
+ style: Optional[Style] = None,
+ key: Optional[Any] = None,
+ id: Optional[Any] = None,
+ class_name: Optional[Any] = None,
+ autofocus: Optional[bool] = None,
+ custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
+ ) -> "ShikiHighLevelCodeBlock":
+ """Create a code block component using [shiki syntax highlighter](https://shiki.matsu.io/).
+
+ Args:
+ *children: The children of the component.
+ use_transformers: If this is enabled, the default transformers(shikijs transformer) will be used.
+ show_line_numbers: If this is enabled line numbers will be shown next to the code block.
+ can_copy: Whether a copy button should appear.
+ copy_button: copy_button: A custom copy button to override the default one.
+ language: The language to use.
+ theme: The theme to use ("light" or "dark").
+ themes: The set of themes to use for different modes.
+ code: The code to display.
+ transformers: The transformers to use for the syntax highlighter.
+ decorations: The decorations to use for the syntax highlighter.
+ style: The style of the component.
+ key: A unique key for the component.
+ id: The id for the component.
+ class_name: The class name for the component.
+ autofocus: Whether the component should take the focus once the page is loaded
+ custom_attrs: custom attribute
+ **props: The props to pass to the component.
+
+ Returns:
+ The code block component.
+ """
+ ...
+
+code_block = CodeblockNamespace()
diff --git a/reflex/components/dynamic.py b/reflex/components/dynamic.py
new file mode 100644
index 000000000..c0e172224
--- /dev/null
+++ b/reflex/components/dynamic.py
@@ -0,0 +1,190 @@
+"""Components that are dynamically generated on the backend."""
+
+from typing import TYPE_CHECKING, Union
+
+from reflex import constants
+from reflex.utils import imports
+from reflex.utils.exceptions import DynamicComponentMissingLibrary
+from reflex.utils.format import format_library_name
+from reflex.utils.serializers import serializer
+from reflex.vars import Var, get_unique_variable_name
+from reflex.vars.base import VarData, transform
+
+if TYPE_CHECKING:
+ from reflex.components.component import Component
+
+
+def get_cdn_url(lib: str) -> str:
+ """Get the CDN URL for a library.
+
+ Args:
+ lib: The library to get the CDN URL for.
+
+ Returns:
+ The CDN URL for the library.
+ """
+ return f"https://cdn.jsdelivr.net/npm/{lib}" + "/+esm"
+
+
+bundled_libraries = {"react", "@radix-ui/themes", "@emotion/react", "next/link"}
+
+
+def bundle_library(component: Union["Component", str]):
+ """Bundle a library with the component.
+
+ Args:
+ component: The component to bundle the library with.
+
+ Raises:
+ DynamicComponentMissingLibrary: Raised when a dynamic component is missing a library.
+ """
+ if isinstance(component, str):
+ bundled_libraries.add(component)
+ return
+ if component.library is None:
+ raise DynamicComponentMissingLibrary("Component must have a library to bundle.")
+ bundled_libraries.add(format_library_name(component.library))
+
+
+def load_dynamic_serializer():
+ """Load the serializer for dynamic components."""
+ # Causes a circular import, so we import here.
+ from reflex.components.component import Component
+
+ @serializer
+ def make_component(component: Component) -> str:
+ """Generate the code for a dynamic component.
+
+ Args:
+ component: The component to generate code for.
+
+ Returns:
+ The generated code
+ """
+ # Causes a circular import, so we import here.
+ from reflex.compiler import templates, utils
+ from reflex.components.base.bare import Bare
+
+ component = Bare.create(Var.create(component))
+
+ rendered_components = {}
+ # Include dynamic imports in the shared component.
+ if dynamic_imports := component._get_all_dynamic_imports():
+ rendered_components.update(
+ {dynamic_import: None for dynamic_import in dynamic_imports}
+ )
+
+ # Include custom code in the shared component.
+ rendered_components.update(
+ {code: None for code in component._get_all_custom_code()},
+ )
+
+ rendered_components[
+ templates.STATEFUL_COMPONENT.render(
+ tag_name="MySSRComponent",
+ memo_trigger_hooks=[],
+ component=component,
+ )
+ ] = None
+
+ libs_in_window = bundled_libraries
+
+ imports = {}
+ for lib, names in component._get_all_imports().items():
+ formatted_lib_name = format_library_name(lib)
+ if (
+ not lib.startswith((".", "/", "$/"))
+ and not lib.startswith("http")
+ and formatted_lib_name not in libs_in_window
+ ):
+ imports[get_cdn_url(lib)] = names
+ else:
+ imports[lib] = names
+
+ module_code_lines = templates.STATEFUL_COMPONENTS.render(
+ imports=utils.compile_imports(imports),
+ memoized_code="\n".join(rendered_components),
+ ).splitlines()[1:]
+
+ # Rewrite imports from `/` to destructure from window
+ for ix, line in enumerate(module_code_lines[:]):
+ if line.startswith("import "):
+ if 'from "$/' in line or 'from "/' in line:
+ module_code_lines[ix] = (
+ line.replace("import ", "const ", 1).replace(
+ " from ", " = window['__reflex'][", 1
+ )
+ + "]"
+ )
+ else:
+ for lib in libs_in_window:
+ if f'from "{lib}"' in line:
+ module_code_lines[ix] = (
+ line.replace("import ", "const ", 1)
+ .replace(
+ f' from "{lib}"', f" = window.__reflex['{lib}']", 1
+ )
+ .replace(" as ", ": ")
+ )
+ if line.startswith("export function"):
+ module_code_lines[ix] = line.replace(
+ "export function", "export default function", 1
+ )
+ line_stripped = line.strip()
+ if line_stripped.startswith("{") and line_stripped.endswith("}"):
+ module_code_lines[ix] = line_stripped[1:-1]
+
+ module_code_lines.insert(0, "const React = window.__reflex.react;")
+
+ return "\n".join(
+ [
+ "//__reflex_evaluate",
+ *module_code_lines,
+ ]
+ )
+
+ @transform
+ def evaluate_component(js_string: Var[str]) -> Var[Component]:
+ """Evaluate a component.
+
+ Args:
+ js_string: The JavaScript string to evaluate.
+
+ Returns:
+ The evaluated JavaScript string.
+ """
+ unique_var_name = get_unique_variable_name()
+
+ return js_string._replace(
+ _js_expr=unique_var_name,
+ _var_type=Component,
+ merge_var_data=VarData.merge(
+ VarData(
+ imports={
+ f"$/{constants.Dirs.STATE_PATH}": [
+ imports.ImportVar(tag="evalReactComponent"),
+ ],
+ "react": [
+ imports.ImportVar(tag="useState"),
+ imports.ImportVar(tag="useEffect"),
+ ],
+ },
+ hooks={
+ f"const [{unique_var_name}, set_{unique_var_name}] = useState(null);": None,
+ "useEffect(() => {"
+ "let isMounted = true;"
+ f"evalReactComponent({str(js_string)})"
+ ".then((component) => {"
+ "if (isMounted) {"
+ f"set_{unique_var_name}(component);"
+ "}"
+ "});"
+ "return () => {"
+ "isMounted = false;"
+ "};"
+ "}"
+ f", [{str(js_string)}]);": None,
+ },
+ ),
+ ),
+ )
diff --git a/reflex/components/el/__init__.py b/reflex/components/el/__init__.py
index 6b6517f77..750e65dba 100644
--- a/reflex/components/el/__init__.py
+++ b/reflex/components/el/__init__.py
@@ -1,3 +1,18 @@
"""The el package exports raw HTML elements."""
-from .elements import *
+from __future__ import annotations
+
+from reflex.utils import lazy_loader
+
+from . import elements
+
+_SUBMODULES: set[str] = {"elements"}
+_SUBMOD_ATTRS: dict[str, list[str]] = {
+ f"elements.{k}": v for k, v in elements._MAPPING.items()
+}
+
+__getattr__, __dir__, __all__ = lazy_loader.attach(
+ __name__,
+ submodules=_SUBMODULES,
+ submod_attrs=_SUBMOD_ATTRS,
+)
diff --git a/reflex/components/el/__init__.pyi b/reflex/components/el/__init__.pyi
new file mode 100644
index 000000000..4815bcd27
--- /dev/null
+++ b/reflex/components/el/__init__.pyi
@@ -0,0 +1,225 @@
+"""Stub file for reflex/components/el/__init__.py"""
+# ------------------- DO NOT EDIT ----------------------
+# This file was generated by `reflex/utils/pyi_generator.py`!
+# ------------------------------------------------------
+
+from . import elements as elements
+from .elements.forms import Button as Button
+from .elements.forms import Fieldset as Fieldset
+from .elements.forms import Form as Form
+from .elements.forms import Input as Input
+from .elements.forms import Label as Label
+from .elements.forms import Legend as Legend
+from .elements.forms import Meter as Meter
+from .elements.forms import Optgroup as Optgroup
+from .elements.forms import Option as Option
+from .elements.forms import Output as Output
+from .elements.forms import Progress as Progress
+from .elements.forms import Select as Select
+from .elements.forms import Textarea as Textarea
+from .elements.forms import button as button
+from .elements.forms import fieldset as fieldset
+from .elements.forms import form as form
+from .elements.forms import input as input
+from .elements.forms import label as label
+from .elements.forms import legend as legend
+from .elements.forms import meter as meter
+from .elements.forms import optgroup as optgroup
+from .elements.forms import option as option
+from .elements.forms import output as output
+from .elements.forms import progress as progress
+from .elements.forms import select as select
+from .elements.forms import textarea as textarea
+from .elements.inline import A as A
+from .elements.inline import Abbr as Abbr
+from .elements.inline import B as B
+from .elements.inline import Bdi as Bdi
+from .elements.inline import Bdo as Bdo
+from .elements.inline import Br as Br
+from .elements.inline import Cite as Cite
+from .elements.inline import Code as Code
+from .elements.inline import Data as Data
+from .elements.inline import Dfn as Dfn
+from .elements.inline import Em as Em
+from .elements.inline import I as I
+from .elements.inline import Kbd as Kbd
+from .elements.inline import Mark as Mark
+from .elements.inline import Q as Q
+from .elements.inline import Rp as Rp
+from .elements.inline import Rt as Rt
+from .elements.inline import Ruby as Ruby
+from .elements.inline import S as S
+from .elements.inline import Samp as Samp
+from .elements.inline import Small as Small
+from .elements.inline import Span as Span
+from .elements.inline import Strong as Strong
+from .elements.inline import Sub as Sub
+from .elements.inline import Sup as Sup
+from .elements.inline import Time as Time
+from .elements.inline import U as U
+from .elements.inline import Wbr as Wbr
+from .elements.inline import a as a
+from .elements.inline import abbr as abbr
+from .elements.inline import b as b
+from .elements.inline import bdi as bdi
+from .elements.inline import bdo as bdo
+from .elements.inline import br as br
+from .elements.inline import cite as cite
+from .elements.inline import code as code
+from .elements.inline import data as data
+from .elements.inline import dfn as dfn
+from .elements.inline import em as em
+from .elements.inline import i as i
+from .elements.inline import kbd as kbd
+from .elements.inline import mark as mark
+from .elements.inline import q as q
+from .elements.inline import rp as rp
+from .elements.inline import rt as rt
+from .elements.inline import ruby as ruby
+from .elements.inline import s as s
+from .elements.inline import samp as samp
+from .elements.inline import small as small
+from .elements.inline import span as span
+from .elements.inline import strong as strong
+from .elements.inline import sub as sub
+from .elements.inline import sup as sup
+from .elements.inline import time as time
+from .elements.inline import u as u
+from .elements.inline import wbr as wbr
+from .elements.media import Area as Area
+from .elements.media import Audio as Audio
+from .elements.media import Embed as Embed
+from .elements.media import Iframe as Iframe
+from .elements.media import Img as Img
+from .elements.media import Map as Map
+from .elements.media import Object as Object
+from .elements.media import Picture as Picture
+from .elements.media import Portal as Portal
+from .elements.media import Source as Source
+from .elements.media import Svg as Svg
+from .elements.media import Track as Track
+from .elements.media import Video as Video
+from .elements.media import area as area
+from .elements.media import audio as audio
+from .elements.media import embed as embed
+from .elements.media import iframe as iframe
+from .elements.media import image as image
+from .elements.media import img as img
+from .elements.media import map as map
+from .elements.media import object as object
+from .elements.media import picture as picture
+from .elements.media import portal as portal
+from .elements.media import source as source
+from .elements.media import svg as svg
+from .elements.media import track as track
+from .elements.media import video as video
+from .elements.metadata import Base as Base
+from .elements.metadata import Head as Head
+from .elements.metadata import Link as Link
+from .elements.metadata import Meta as Meta
+from .elements.metadata import Style as Style
+from .elements.metadata import Title as Title
+from .elements.metadata import base as base
+from .elements.metadata import head as head
+from .elements.metadata import link as link
+from .elements.metadata import meta as meta
+from .elements.metadata import style as style
+from .elements.metadata import title as title
+from .elements.other import Details as Details
+from .elements.other import Dialog as Dialog
+from .elements.other import Html as Html
+from .elements.other import Math as Math
+from .elements.other import Slot as Slot
+from .elements.other import Summary as Summary
+from .elements.other import Template as Template
+from .elements.other import details as details
+from .elements.other import dialog as dialog
+from .elements.other import html as html
+from .elements.other import math as math
+from .elements.other import slot as slot
+from .elements.other import summary as summary
+from .elements.other import template as template
+from .elements.scripts import Canvas as Canvas
+from .elements.scripts import Noscript as Noscript
+from .elements.scripts import Script as Script
+from .elements.scripts import canvas as canvas
+from .elements.scripts import noscript as noscript
+from .elements.scripts import script as script
+from .elements.sectioning import H1 as H1
+from .elements.sectioning import H2 as H2
+from .elements.sectioning import H3 as H3
+from .elements.sectioning import H4 as H4
+from .elements.sectioning import H5 as H5
+from .elements.sectioning import H6 as H6
+from .elements.sectioning import Address as Address
+from .elements.sectioning import Article as Article
+from .elements.sectioning import Aside as Aside
+from .elements.sectioning import Body as Body
+from .elements.sectioning import Footer as Footer
+from .elements.sectioning import Header as Header
+from .elements.sectioning import Main as Main
+from .elements.sectioning import Nav as Nav
+from .elements.sectioning import Section as Section
+from .elements.sectioning import address as address
+from .elements.sectioning import article as article
+from .elements.sectioning import aside as aside
+from .elements.sectioning import body as body
+from .elements.sectioning import footer as footer
+from .elements.sectioning import h1 as h1
+from .elements.sectioning import h2 as h2
+from .elements.sectioning import h3 as h3
+from .elements.sectioning import h4 as h4
+from .elements.sectioning import h5 as h5
+from .elements.sectioning import h6 as h6
+from .elements.sectioning import header as header
+from .elements.sectioning import main as main
+from .elements.sectioning import nav as nav
+from .elements.sectioning import section as section
+from .elements.tables import Caption as Caption
+from .elements.tables import Col as Col
+from .elements.tables import Colgroup as Colgroup
+from .elements.tables import Table as Table
+from .elements.tables import Tbody as Tbody
+from .elements.tables import Td as Td
+from .elements.tables import Tfoot as Tfoot
+from .elements.tables import Th as Th
+from .elements.tables import Thead as Thead
+from .elements.tables import Tr as Tr
+from .elements.tables import caption as caption
+from .elements.tables import col as col
+from .elements.tables import colgroup as colgroup
+from .elements.tables import table as table
+from .elements.tables import tbody as tbody
+from .elements.tables import td as td
+from .elements.tables import tfoot as tfoot
+from .elements.tables import th as th
+from .elements.tables import thead as thead
+from .elements.tables import tr as tr
+from .elements.typography import Blockquote as Blockquote
+from .elements.typography import Dd as Dd
+from .elements.typography import Del as Del
+from .elements.typography import Div as Div
+from .elements.typography import Dl as Dl
+from .elements.typography import Dt as Dt
+from .elements.typography import Figcaption as Figcaption
+from .elements.typography import Hr as Hr
+from .elements.typography import Ins as Ins
+from .elements.typography import Li as Li
+from .elements.typography import Ol as Ol
+from .elements.typography import P as P
+from .elements.typography import Pre as Pre
+from .elements.typography import Ul as Ul
+from .elements.typography import blockquote as blockquote
+from .elements.typography import dd as dd
+from .elements.typography import del_ as del_
+from .elements.typography import div as div
+from .elements.typography import dl as dl
+from .elements.typography import dt as dt
+from .elements.typography import figcaption as figcaption
+from .elements.typography import hr as hr
+from .elements.typography import ins as ins
+from .elements.typography import li as li
+from .elements.typography import ol as ol
+from .elements.typography import p as p
+from .elements.typography import pre as pre
+from .elements.typography import ul as ul
diff --git a/reflex/components/el/element.py b/reflex/components/el/element.py
index c95965f4a..213cea65a 100644
--- a/reflex/components/el/element.py
+++ b/reflex/components/el/element.py
@@ -1,6 +1,5 @@
"""Base class definition for raw HTML elements."""
-
from reflex.components.component import Component
diff --git a/reflex/components/el/element.pyi b/reflex/components/el/element.pyi
index c6ebaacec..f6d76cd02 100644
--- a/reflex/components/el/element.pyi
+++ b/reflex/components/el/element.pyi
@@ -1,13 +1,14 @@
"""Stub file for reflex/components/el/element.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
from reflex.components.component import Component
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
class Element(Component):
@overload
@@ -21,52 +22,22 @@ class Element(Component):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Element":
"""Create the component.
diff --git a/reflex/components/el/elements/__init__.py b/reflex/components/el/elements/__init__.py
index 240990280..17fdb77ca 100644
--- a/reflex/components/el/elements/__init__.py
+++ b/reflex/components/el/elements/__init__.py
@@ -1,227 +1,137 @@
"""Element classes."""
-from .forms import (
- Button,
- Fieldset,
- Form,
- Input,
- Label,
- Legend,
- Meter,
- Optgroup,
- Option,
- Output,
- Progress,
- Select,
- Textarea,
+
+from __future__ import annotations
+
+from reflex.utils import lazy_loader
+
+_MAPPING = {
+ "forms": [
+ "button",
+ "fieldset",
+ "form",
+ "input",
+ "label",
+ "legend",
+ "meter",
+ "optgroup",
+ "option",
+ "output",
+ "progress",
+ "select",
+ "textarea",
+ ],
+ "inline": [
+ "a",
+ "abbr",
+ "b",
+ "bdi",
+ "bdo",
+ "br",
+ "cite",
+ "code",
+ "data",
+ "dfn",
+ "em",
+ "i",
+ "kbd",
+ "mark",
+ "q",
+ "rp",
+ "rt",
+ "ruby",
+ "s",
+ "samp",
+ "small",
+ "span",
+ "strong",
+ "sub",
+ "sup",
+ "time",
+ "u",
+ "wbr",
+ ],
+ "media": [
+ "area",
+ "audio",
+ "img",
+ "image",
+ "map",
+ "track",
+ "video",
+ "embed",
+ "iframe",
+ "object",
+ "picture",
+ "portal",
+ "source",
+ "svg",
+ ],
+ "metadata": [
+ "base",
+ "head",
+ "link",
+ "meta",
+ "title",
+ "style",
+ ],
+ "other": ["details", "dialog", "summary", "slot", "template", "math", "html"],
+ "scripts": ["canvas", "noscript", "script"],
+ "sectioning": [
+ "address",
+ "article",
+ "aside",
+ "body",
+ "header",
+ "footer",
+ "h1",
+ "h2",
+ "h3",
+ "h4",
+ "h5",
+ "h6",
+ "main",
+ "nav",
+ "section",
+ ],
+ "tables": [
+ "caption",
+ "col",
+ "colgroup",
+ "table",
+ "td",
+ "tfoot",
+ "th",
+ "thead",
+ "tr",
+ "tbody",
+ ],
+ "typography": [
+ "blockquote",
+ "dd",
+ "div",
+ "dl",
+ "dt",
+ "figcaption",
+ "hr",
+ "ol",
+ "li",
+ "p",
+ "pre",
+ "ul",
+ "ins",
+ "del_",
+ "Del",
+ ],
+}
+
+
+EXCLUDE = ["del_", "Del", "image"]
+for _, v in _MAPPING.items():
+ v.extend([mod.capitalize() for mod in v if mod not in EXCLUDE])
+
+_SUBMOD_ATTRS: dict[str, list[str]] = _MAPPING
+
+__getattr__, __dir__, __all__ = lazy_loader.attach(
+ __name__,
+ submod_attrs=_SUBMOD_ATTRS,
)
-from .inline import (
- A,
- Abbr,
- B,
- Bdi,
- Bdo,
- Br,
- Cite,
- Code,
- Data,
- Dfn,
- Em,
- I,
- Kbd,
- Mark,
- Q,
- Rp,
- Rt,
- Ruby,
- S,
- Samp,
- Small,
- Span,
- Strong,
- Sub,
- Sup,
- Time,
- U,
- Wbr,
-)
-from .media import (
- Area,
- Audio,
- Embed,
- Iframe,
- Img,
- Map,
- Object,
- Path,
- Picture,
- Portal,
- Source,
- Svg,
- Track,
- Video,
-)
-from .metadata import Base, Head, Link, Meta, Title
-from .other import Details, Dialog, Html, Math, Slot, Summary, Template
-from .scripts import Canvas, Noscript, Script
-from .sectioning import (
- H1,
- H2,
- H3,
- H4,
- H5,
- H6,
- Address,
- Article,
- Aside,
- Body,
- Footer,
- Header,
- Main,
- Nav,
- Section,
-)
-from .tables import Caption, Col, Colgroup, Table, Tbody, Td, Tfoot, Th, Thead, Tr
-from .typography import (
- Blockquote,
- Dd,
- Del,
- Div,
- Dl,
- Dt,
- Figcaption,
- Hr,
- Ins,
- Li,
- Ol,
- P,
- Pre,
- Ul,
-)
-
-# Forms
-button = Button.create
-fieldset = Fieldset.create
-form = Form.create
-input = Input.create
-label = Label.create
-legend = Legend.create
-meter = Meter.create
-optgroup = Optgroup.create
-option = Option.create
-output = Output.create
-progress = Progress.create
-select = Select.create
-textarea = Textarea.create
-
-# Tables
-caption = Caption.create
-col = Col.create
-colgroup = Colgroup.create
-table = Table.create
-tbody = Tbody.create
-td = Td.create
-tfoot = Tfoot.create
-th = Th.create
-thead = Thead.create
-tr = Tr.create
-
-# Media
-area = Area.create
-audio = Audio.create
-img = Img.create
-map = Map.create
-track = Track.create
-video = Video.create
-embed = Embed.create
-iframe = Iframe.create
-object = Object.create
-picture = Picture.create
-portal = Portal.create
-source = Source.create
-svg = Svg.create
-path = Path.create
-
-# Sectioning
-address = Address.create
-article = Article.create
-aside = Aside.create
-body = Body.create
-header = Header.create
-footer = Footer.create
-
-# Typography
-blockquote = Blockquote.create
-dd = Dd.create
-div = Div.create
-dl = Dl.create
-dt = Dt.create
-figcaption = Figcaption.create
-hr = Hr.create
-li = Li.create
-ol = Ol.create
-p = P.create
-pre = Pre.create
-ul = Ul.create
-ins = Ins.create
-del_ = Del.create # 'del' is a reserved keyword in Python
-h1 = H1.create
-h2 = H2.create
-h3 = H3.create
-h4 = H4.create
-h5 = H5.create
-h6 = H6.create
-main = Main.create
-nav = Nav.create
-section = Section.create
-
-# Inline
-a = A.create
-abbr = Abbr.create
-b = B.create
-bdi = Bdi.create
-bdo = Bdo.create
-br = Br.create
-cite = Cite.create
-code = Code.create
-data = Data.create
-dfn = Dfn.create
-em = Em.create
-i = I.create
-kbd = Kbd.create
-mark = Mark.create
-q = Q.create
-rp = Rp.create
-rt = Rt.create
-ruby = Ruby.create
-s = S.create
-samp = Samp.create
-small = Small.create
-span = Span.create
-strong = Strong.create
-sub = Sub.create
-sup = Sup.create
-time = Time.create
-u = U.create
-wbr = Wbr.create
-
-# Metadata
-base = Base.create
-head = Head.create
-link = Link.create
-meta = Meta.create
-title = Title.create
-
-# Scripts
-canvas = Canvas.create
-noscript = Noscript.create
-script = Script.create
-
-# Other
-details = Details.create
-dialog = Dialog.create
-summary = Summary.create
-slot = Slot.create
-template = Template.create
-svg = Svg.create
-math = Math.create
-html = Html.create
diff --git a/reflex/components/el/elements/__init__.pyi b/reflex/components/el/elements/__init__.pyi
new file mode 100644
index 000000000..b35e70dd2
--- /dev/null
+++ b/reflex/components/el/elements/__init__.pyi
@@ -0,0 +1,340 @@
+"""Stub file for reflex/components/el/elements/__init__.py"""
+# ------------------- DO NOT EDIT ----------------------
+# This file was generated by `reflex/utils/pyi_generator.py`!
+# ------------------------------------------------------
+
+from .forms import Button as Button
+from .forms import Fieldset as Fieldset
+from .forms import Form as Form
+from .forms import Input as Input
+from .forms import Label as Label
+from .forms import Legend as Legend
+from .forms import Meter as Meter
+from .forms import Optgroup as Optgroup
+from .forms import Option as Option
+from .forms import Output as Output
+from .forms import Progress as Progress
+from .forms import Select as Select
+from .forms import Textarea as Textarea
+from .forms import button as button
+from .forms import fieldset as fieldset
+from .forms import form as form
+from .forms import input as input
+from .forms import label as label
+from .forms import legend as legend
+from .forms import meter as meter
+from .forms import optgroup as optgroup
+from .forms import option as option
+from .forms import output as output
+from .forms import progress as progress
+from .forms import select as select
+from .forms import textarea as textarea
+from .inline import A as A
+from .inline import Abbr as Abbr
+from .inline import B as B
+from .inline import Bdi as Bdi
+from .inline import Bdo as Bdo
+from .inline import Br as Br
+from .inline import Cite as Cite
+from .inline import Code as Code
+from .inline import Data as Data
+from .inline import Dfn as Dfn
+from .inline import Em as Em
+from .inline import I as I
+from .inline import Kbd as Kbd
+from .inline import Mark as Mark
+from .inline import Q as Q
+from .inline import Rp as Rp
+from .inline import Rt as Rt
+from .inline import Ruby as Ruby
+from .inline import S as S
+from .inline import Samp as Samp
+from .inline import Small as Small
+from .inline import Span as Span
+from .inline import Strong as Strong
+from .inline import Sub as Sub
+from .inline import Sup as Sup
+from .inline import Time as Time
+from .inline import U as U
+from .inline import Wbr as Wbr
+from .inline import a as a
+from .inline import abbr as abbr
+from .inline import b as b
+from .inline import bdi as bdi
+from .inline import bdo as bdo
+from .inline import br as br
+from .inline import cite as cite
+from .inline import code as code
+from .inline import data as data
+from .inline import dfn as dfn
+from .inline import em as em
+from .inline import i as i
+from .inline import kbd as kbd
+from .inline import mark as mark
+from .inline import q as q
+from .inline import rp as rp
+from .inline import rt as rt
+from .inline import ruby as ruby
+from .inline import s as s
+from .inline import samp as samp
+from .inline import small as small
+from .inline import span as span
+from .inline import strong as strong
+from .inline import sub as sub
+from .inline import sup as sup
+from .inline import time as time
+from .inline import u as u
+from .inline import wbr as wbr
+from .media import Area as Area
+from .media import Audio as Audio
+from .media import Embed as Embed
+from .media import Iframe as Iframe
+from .media import Img as Img
+from .media import Map as Map
+from .media import Object as Object
+from .media import Picture as Picture
+from .media import Portal as Portal
+from .media import Source as Source
+from .media import Svg as Svg
+from .media import Track as Track
+from .media import Video as Video
+from .media import area as area
+from .media import audio as audio
+from .media import embed as embed
+from .media import iframe as iframe
+from .media import image as image
+from .media import img as img
+from .media import map as map
+from .media import object as object
+from .media import picture as picture
+from .media import portal as portal
+from .media import source as source
+from .media import svg as svg
+from .media import track as track
+from .media import video as video
+from .metadata import Base as Base
+from .metadata import Head as Head
+from .metadata import Link as Link
+from .metadata import Meta as Meta
+from .metadata import Style as Style
+from .metadata import Title as Title
+from .metadata import base as base
+from .metadata import head as head
+from .metadata import link as link
+from .metadata import meta as meta
+from .metadata import style as style
+from .metadata import title as title
+from .other import Details as Details
+from .other import Dialog as Dialog
+from .other import Html as Html
+from .other import Math as Math
+from .other import Slot as Slot
+from .other import Summary as Summary
+from .other import Template as Template
+from .other import details as details
+from .other import dialog as dialog
+from .other import html as html
+from .other import math as math
+from .other import slot as slot
+from .other import summary as summary
+from .other import template as template
+from .scripts import Canvas as Canvas
+from .scripts import Noscript as Noscript
+from .scripts import Script as Script
+from .scripts import canvas as canvas
+from .scripts import noscript as noscript
+from .scripts import script as script
+from .sectioning import H1 as H1
+from .sectioning import H2 as H2
+from .sectioning import H3 as H3
+from .sectioning import H4 as H4
+from .sectioning import H5 as H5
+from .sectioning import H6 as H6
+from .sectioning import Address as Address
+from .sectioning import Article as Article
+from .sectioning import Aside as Aside
+from .sectioning import Body as Body
+from .sectioning import Footer as Footer
+from .sectioning import Header as Header
+from .sectioning import Main as Main
+from .sectioning import Nav as Nav
+from .sectioning import Section as Section
+from .sectioning import address as address
+from .sectioning import article as article
+from .sectioning import aside as aside
+from .sectioning import body as body
+from .sectioning import footer as footer
+from .sectioning import h1 as h1
+from .sectioning import h2 as h2
+from .sectioning import h3 as h3
+from .sectioning import h4 as h4
+from .sectioning import h5 as h5
+from .sectioning import h6 as h6
+from .sectioning import header as header
+from .sectioning import main as main
+from .sectioning import nav as nav
+from .sectioning import section as section
+from .tables import Caption as Caption
+from .tables import Col as Col
+from .tables import Colgroup as Colgroup
+from .tables import Table as Table
+from .tables import Tbody as Tbody
+from .tables import Td as Td
+from .tables import Tfoot as Tfoot
+from .tables import Th as Th
+from .tables import Thead as Thead
+from .tables import Tr as Tr
+from .tables import caption as caption
+from .tables import col as col
+from .tables import colgroup as colgroup
+from .tables import table as table
+from .tables import tbody as tbody
+from .tables import td as td
+from .tables import tfoot as tfoot
+from .tables import th as th
+from .tables import thead as thead
+from .tables import tr as tr
+from .typography import Blockquote as Blockquote
+from .typography import Dd as Dd
+from .typography import Del as Del
+from .typography import Div as Div
+from .typography import Dl as Dl
+from .typography import Dt as Dt
+from .typography import Figcaption as Figcaption
+from .typography import Hr as Hr
+from .typography import Ins as Ins
+from .typography import Li as Li
+from .typography import Ol as Ol
+from .typography import P as P
+from .typography import Pre as Pre
+from .typography import Ul as Ul
+from .typography import blockquote as blockquote
+from .typography import dd as dd
+from .typography import del_ as del_
+from .typography import div as div
+from .typography import dl as dl
+from .typography import dt as dt
+from .typography import figcaption as figcaption
+from .typography import hr as hr
+from .typography import ins as ins
+from .typography import li as li
+from .typography import ol as ol
+from .typography import p as p
+from .typography import pre as pre
+from .typography import ul as ul
+
+_MAPPING = {
+ "forms": [
+ "button",
+ "fieldset",
+ "form",
+ "input",
+ "label",
+ "legend",
+ "meter",
+ "optgroup",
+ "option",
+ "output",
+ "progress",
+ "select",
+ "textarea",
+ ],
+ "inline": [
+ "a",
+ "abbr",
+ "b",
+ "bdi",
+ "bdo",
+ "br",
+ "cite",
+ "code",
+ "data",
+ "dfn",
+ "em",
+ "i",
+ "kbd",
+ "mark",
+ "q",
+ "rp",
+ "rt",
+ "ruby",
+ "s",
+ "samp",
+ "small",
+ "span",
+ "strong",
+ "sub",
+ "sup",
+ "time",
+ "u",
+ "wbr",
+ ],
+ "media": [
+ "area",
+ "audio",
+ "img",
+ "image",
+ "map",
+ "track",
+ "video",
+ "embed",
+ "iframe",
+ "object",
+ "picture",
+ "portal",
+ "source",
+ "svg",
+ ],
+ "metadata": ["base", "head", "link", "meta", "title", "style"],
+ "other": ["details", "dialog", "summary", "slot", "template", "math", "html"],
+ "scripts": ["canvas", "noscript", "script"],
+ "sectioning": [
+ "address",
+ "article",
+ "aside",
+ "body",
+ "header",
+ "footer",
+ "h1",
+ "h2",
+ "h3",
+ "h4",
+ "h5",
+ "h6",
+ "main",
+ "nav",
+ "section",
+ ],
+ "tables": [
+ "caption",
+ "col",
+ "colgroup",
+ "table",
+ "td",
+ "tfoot",
+ "th",
+ "thead",
+ "tr",
+ "tbody",
+ ],
+ "typography": [
+ "blockquote",
+ "dd",
+ "div",
+ "dl",
+ "dt",
+ "figcaption",
+ "hr",
+ "ol",
+ "li",
+ "p",
+ "pre",
+ "ul",
+ "ins",
+ "del_",
+ "Del",
+ ],
+}
+EXCLUDE = ["del_", "Del", "image"]
+for _, v in _MAPPING.items():
+ v.extend([mod.capitalize() for mod in v if mod not in EXCLUDE])
diff --git a/reflex/components/el/elements/base.py b/reflex/components/el/elements/base.py
index fd2dc8cbb..a9748ae25 100644
--- a/reflex/components/el/elements/base.py
+++ b/reflex/components/el/elements/base.py
@@ -1,8 +1,9 @@
"""Element classes. This is an auto-generated file. Do not edit. See ../generate.py."""
+
from typing import Union
from reflex.components.el.element import Element
-from reflex.vars import Var as Var
+from reflex.vars.base import Var
class BaseHTML(Element):
diff --git a/reflex/components/el/elements/base.pyi b/reflex/components/el/elements/base.pyi
index 9b6d0d6d8..6e943d0d0 100644
--- a/reflex/components/el/elements/base.pyi
+++ b/reflex/components/el/elements/base.pyi
@@ -1,15 +1,14 @@
"""Stub file for reflex/components/el/elements/base.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Union
from reflex.components.el.element import Element
-from reflex.vars import Var as Var
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
class BaseHTML(Element):
@overload
@@ -17,98 +16,52 @@ class BaseHTML(Element):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "BaseHTML":
"""Create the component.
diff --git a/reflex/components/el/elements/forms.py b/reflex/components/el/elements/forms.py
index a98bd47c7..4caf14b41 100644
--- a/reflex/components/el/elements/forms.py
+++ b/reflex/components/el/elements/forms.py
@@ -3,29 +3,35 @@
from __future__ import annotations
from hashlib import md5
-from typing import Any, Dict, Iterator, Set, Union
+from typing import Any, Dict, Iterator, Set, Tuple, Union
from jinja2 import Environment
from reflex.components.el.element import Element
from reflex.components.tags.tag import Tag
from reflex.constants import Dirs, EventTriggers
-from reflex.event import EventChain
-from reflex.utils import imports
-from reflex.utils.format import format_event_chain
-from reflex.vars import BaseVar, Var
+from reflex.event import (
+ EventChain,
+ EventHandler,
+ input_event,
+ key_event,
+ prevent_default,
+)
+from reflex.utils.imports import ImportDict
+from reflex.vars import VarData
+from reflex.vars.base import LiteralVar, Var
from .base import BaseHTML
-FORM_DATA = Var.create("form_data")
+FORM_DATA = Var(_js_expr="form_data")
HANDLE_SUBMIT_JS_JINJA2 = Environment().from_string(
"""
const handleSubmit_{{ handle_submit_unique_name }} = useCallback((ev) => {
const $form = ev.target
ev.preventDefault()
- const {{ form_data }} = {...Object.fromEntries(new FormData($form).entries()), ...{{ field_ref_mapping }}}
+ const {{ form_data }} = {...Object.fromEntries(new FormData($form).entries()), ...{{ field_ref_mapping }}};
- {{ on_submit_event_chain }}
+ ({{ on_submit_event_chain }}());
if ({{ reset_on_submit }}) {
$form.reset()
@@ -96,6 +102,24 @@ class Fieldset(Element):
name: Var[Union[str, int, bool]]
+def on_submit_event_spec() -> Tuple[Var[Dict[str, Any]]]:
+ """Event handler spec for the on_submit event.
+
+ Returns:
+ The event handler spec.
+ """
+ return (FORM_DATA,)
+
+
+def on_submit_string_event_spec() -> Tuple[Var[Dict[str, str]]]:
+ """Event handler spec for the on_submit event.
+
+ Returns:
+ The event handler spec.
+ """
+ return (FORM_DATA,)
+
+
class Form(BaseHTML):
"""Display the form element."""
@@ -134,16 +158,8 @@ class Form(BaseHTML):
# The name used to make this form's submit handler function unique.
handle_submit_unique_name: Var[str]
- def get_event_triggers(self) -> Dict[str, Any]:
- """Event triggers for radix form root.
-
- Returns:
- The triggers for event supported by Root.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_SUBMIT: lambda e0: [FORM_DATA],
- }
+ # Fired when the form is submitted
+ on_submit: EventHandler[on_submit_event_spec, on_submit_string_event_spec]
@classmethod
def create(cls, *children, **props):
@@ -156,6 +172,9 @@ class Form(BaseHTML):
Returns:
The form component.
"""
+ if "on_submit" not in props:
+ props["on_submit"] = prevent_default
+
if "handle_submit_unique_name" in props:
return super().create(*children, **props)
@@ -169,38 +188,44 @@ class Form(BaseHTML):
).hexdigest()
return form
- def _get_imports(self) -> imports.ImportDict:
- return imports.merge_imports(
- super()._get_imports(),
- {
- "react": {imports.ImportVar(tag="useCallback")},
- f"/{Dirs.STATE_PATH}": {
- imports.ImportVar(tag="getRefValue"),
- imports.ImportVar(tag="getRefValues"),
- },
- },
- )
+ def add_imports(self) -> ImportDict:
+ """Add imports needed by the form component.
- def _get_hooks(self) -> str | None:
+ Returns:
+ The imports for the form component.
+ """
+ return {
+ "react": "useCallback",
+ f"$/{Dirs.STATE_PATH}": ["getRefValue", "getRefValues"],
+ }
+
+ def add_hooks(self) -> list[str]:
+ """Add hooks for the form.
+
+ Returns:
+ The hooks for the form.
+ """
if EventTriggers.ON_SUBMIT not in self.event_triggers:
- return
- return HANDLE_SUBMIT_JS_JINJA2.render(
- handle_submit_unique_name=self.handle_submit_unique_name,
- form_data=FORM_DATA,
- field_ref_mapping=str(Var.create_safe(self._get_form_refs())),
- on_submit_event_chain=format_event_chain(
- self.event_triggers[EventTriggers.ON_SUBMIT]
- ),
- reset_on_submit=self.reset_on_submit,
- )
+ return []
+ return [
+ HANDLE_SUBMIT_JS_JINJA2.render(
+ handle_submit_unique_name=self.handle_submit_unique_name,
+ form_data=FORM_DATA,
+ field_ref_mapping=str(LiteralVar.create(self._get_form_refs())),
+ on_submit_event_chain=str(
+ LiteralVar.create(self.event_triggers[EventTriggers.ON_SUBMIT])
+ ),
+ reset_on_submit=self.reset_on_submit,
+ )
+ ]
def _render(self) -> Tag:
render_tag = super()._render()
if EventTriggers.ON_SUBMIT in self.event_triggers:
render_tag.add_props(
**{
- EventTriggers.ON_SUBMIT: BaseVar(
- _var_name=f"handleSubmit_{self.handle_submit_unique_name}",
+ EventTriggers.ON_SUBMIT: Var(
+ _js_expr=f"handleSubmit_{self.handle_submit_unique_name}",
_var_type=EventChain,
)
}
@@ -214,15 +239,18 @@ class Form(BaseHTML):
# when ref start with refs_ it's an array of refs, so we need different method
# to collect data
if ref.startswith("refs_"):
- ref_var = Var.create_safe(ref[:-3]).as_ref()
- form_refs[ref[5:-3]] = Var.create_safe(
- f"getRefValues({str(ref_var)})", _var_is_local=False
- )._replace(merge_var_data=ref_var._var_data)
+ ref_var = Var(_js_expr=ref[:-3]).as_ref()
+ form_refs[ref[len("refs_") : -3]] = Var(
+ _js_expr=f"getRefValues({str(ref_var)})",
+ _var_data=VarData.merge(ref_var._get_all_var_data()),
+ )
else:
- ref_var = Var.create_safe(ref).as_ref()
- form_refs[ref[4:]] = Var.create_safe(
- f"getRefValue({str(ref_var)})", _var_is_local=False
- )._replace(merge_var_data=ref_var._var_data)
+ ref_var = Var(_js_expr=ref).as_ref()
+ form_refs[ref[4:]] = Var(
+ _js_expr=f"getRefValue({str(ref_var)})",
+ _var_data=VarData.merge(ref_var._get_all_var_data()),
+ )
+ # print(repr(form_refs))
return form_refs
def _get_vars(self, include_children: bool = True) -> Iterator[Var]:
@@ -340,20 +368,20 @@ class Input(BaseHTML):
# Value of the input
value: Var[Union[str, int, float]]
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the event triggers that pass the component's value to the handler.
+ # Fired when the input value changes
+ on_change: EventHandler[input_event]
- Returns:
- A dict mapping the event trigger to the var that is passed to the handler.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_CHANGE: lambda e0: [e0.target.value],
- EventTriggers.ON_FOCUS: lambda e0: [e0.target.value],
- EventTriggers.ON_BLUR: lambda e0: [e0.target.value],
- EventTriggers.ON_KEY_DOWN: lambda e0: [e0.key],
- EventTriggers.ON_KEY_UP: lambda e0: [e0.key],
- }
+ # Fired when the input gains focus
+ on_focus: EventHandler[input_event]
+
+ # Fired when the input loses focus
+ on_blur: EventHandler[input_event]
+
+ # Fired when a key is pressed down
+ on_key_down: EventHandler[key_event]
+
+ # Fired when a key is released
+ on_key_up: EventHandler[key_event]
class Label(BaseHTML):
@@ -491,23 +519,15 @@ class Select(BaseHTML):
# Number of visible options in a drop-down list
size: Var[Union[str, int, bool]]
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the event triggers that pass the component's value to the handler.
-
- Returns:
- A dict mapping the event trigger to the var that is passed to the handler.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_CHANGE: lambda e0: [e0.target.value],
- }
+ # Fired when the select value changes
+ on_change: EventHandler[input_event]
AUTO_HEIGHT_JS = """
const autoHeightOnInput = (e, is_enabled) => {
if (is_enabled) {
const el = e.target;
- el.style.overflowY = "hidden";
+ el.style.overflowY = "scroll";
el.style.height = "auto";
el.style.height = (e.target.scrollHeight) + "px";
if (el.form && !el.form.data_resize_on_reset) {
@@ -589,6 +609,57 @@ class Textarea(BaseHTML):
# How the text in the textarea is to be wrapped when submitting the form
wrap: Var[Union[str, int, bool]]
+ # Fired when the input value changes
+ on_change: EventHandler[input_event]
+
+ # Fired when the input gains focus
+ on_focus: EventHandler[input_event]
+
+ # Fired when the input loses focus
+ on_blur: EventHandler[input_event]
+
+ # Fired when a key is pressed down
+ on_key_down: EventHandler[key_event]
+
+ # Fired when a key is released
+ on_key_up: EventHandler[key_event]
+
+ @classmethod
+ def create(cls, *children, **props):
+ """Create a textarea component.
+
+ Args:
+ *children: The children of the textarea.
+ **props: The properties of the textarea.
+
+ Returns:
+ The textarea component.
+
+ Raises:
+ ValueError: when `enter_key_submit` is combined with `on_key_down`.
+ """
+ enter_key_submit = props.get("enter_key_submit")
+ auto_height = props.get("auto_height")
+ custom_attrs = props.setdefault("custom_attrs", {})
+
+ if enter_key_submit is not None:
+ enter_key_submit = Var.create(enter_key_submit)
+ if "on_key_down" in props:
+ raise ValueError(
+ "Cannot combine `enter_key_submit` with `on_key_down`.",
+ )
+ custom_attrs["on_key_down"] = Var(
+ _js_expr=f"(e) => enterKeySubmitOnKeyDown(e, {str(enter_key_submit)})",
+ _var_data=VarData.merge(enter_key_submit._get_all_var_data()),
+ )
+ if auto_height is not None:
+ auto_height = Var.create(auto_height)
+ custom_attrs["on_input"] = Var(
+ _js_expr=f"(e) => autoHeightOnInput(e, {str(auto_height)})",
+ _var_data=VarData.merge(auto_height._get_all_var_data()),
+ )
+ return super().create(*children, **props)
+
def _exclude_props(self) -> list[str]:
return super()._exclude_props() + [
"auto_height",
@@ -608,39 +679,17 @@ class Textarea(BaseHTML):
custom_code.add(ENTER_KEY_SUBMIT_JS)
return custom_code
- def _render(self) -> Tag:
- tag = super()._render()
- if self.enter_key_submit is not None:
- if "on_key_down" in self.event_triggers:
- raise ValueError(
- "Cannot combine `enter_key_submit` with `on_key_down`.",
- )
- tag.add_props(
- on_key_down=Var.create_safe(
- f"(e) => enterKeySubmitOnKeyDown(e, {self.enter_key_submit._var_name_unwrapped})",
- _var_is_local=False,
- )._replace(merge_var_data=self.enter_key_submit._var_data),
- )
- if self.auto_height is not None:
- tag.add_props(
- on_input=Var.create_safe(
- f"(e) => autoHeightOnInput(e, {self.auto_height._var_name_unwrapped})",
- _var_is_local=False,
- )._replace(merge_var_data=self.auto_height._var_data),
- )
- return tag
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the event triggers that pass the component's value to the handler.
-
- Returns:
- A dict mapping the event trigger to the var that is passed to the handler.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_CHANGE: lambda e0: [e0.target.value],
- EventTriggers.ON_FOCUS: lambda e0: [e0.target.value],
- EventTriggers.ON_BLUR: lambda e0: [e0.target.value],
- EventTriggers.ON_KEY_DOWN: lambda e0: [e0.key],
- EventTriggers.ON_KEY_UP: lambda e0: [e0.key],
- }
+button = Button.create
+fieldset = Fieldset.create
+form = Form.create
+input = Input.create
+label = Label.create
+legend = Legend.create
+meter = Meter.create
+optgroup = Optgroup.create
+option = Option.create
+output = Output.create
+progress = Progress.create
+select = Select.create
+textarea = Textarea.create
diff --git a/reflex/components/el/elements/forms.pyi b/reflex/components/el/elements/forms.pyi
index 38853ce40..a8e9b6174 100644
--- a/reflex/components/el/elements/forms.pyi
+++ b/reflex/components/el/elements/forms.pyi
@@ -1,27 +1,23 @@
"""Stub file for reflex/components/el/elements/forms.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Tuple, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from hashlib import md5
-from typing import Any, Dict, Iterator, Set, Union
from jinja2 import Environment
+
from reflex.components.el.element import Element
-from reflex.components.tags.tag import Tag
-from reflex.constants import Dirs, EventTriggers
-from reflex.event import EventChain
-from reflex.utils import imports
-from reflex.utils.format import format_event_chain
-from reflex.vars import BaseVar, Var
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.utils.imports import ImportDict
+from reflex.vars.base import Var
+
from .base import BaseHTML
-FORM_DATA = Var.create("form_data")
+FORM_DATA = Var(_js_expr="form_data")
HANDLE_SUBMIT_JS_JINJA2 = Environment().from_string(
- "\n const handleSubmit_{{ handle_submit_unique_name }} = useCallback((ev) => {\n const $form = ev.target\n ev.preventDefault()\n const {{ form_data }} = {...Object.fromEntries(new FormData($form).entries()), ...{{ field_ref_mapping }}}\n\n {{ on_submit_event_chain }}\n\n if ({{ reset_on_submit }}) {\n $form.reset()\n }\n })\n "
+ "\n const handleSubmit_{{ handle_submit_unique_name }} = useCallback((ev) => {\n const $form = ev.target\n ev.preventDefault()\n const {{ form_data }} = {...Object.fromEntries(new FormData($form).entries()), ...{{ field_ref_mapping }}};\n\n ({{ on_submit_event_chain }}());\n\n if ({{ reset_on_submit }}) {\n $form.reset()\n }\n })\n "
)
class Button(BaseHTML):
@@ -30,123 +26,67 @@ class Button(BaseHTML):
def create( # type: ignore
cls,
*children,
- auto_focus: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ auto_focus: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
disabled: Optional[Union[Var[bool], bool]] = None,
- form: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- form_action: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ form: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ form_action: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
form_enc_type: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- form_method: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ form_method: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
form_no_validate: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- form_target: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- name: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- type: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- value: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ form_target: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ name: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ type: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ value: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Button":
"""Create the component.
@@ -198,98 +138,52 @@ class Datalist(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Datalist":
"""Create the component.
@@ -330,63 +224,31 @@ class Fieldset(Element):
def create( # type: ignore
cls,
*children,
- disabled: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- form: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- name: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
+ disabled: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ form: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ name: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Fieldset":
"""Create the component.
@@ -408,135 +270,79 @@ class Fieldset(Element):
"""
...
+def on_submit_event_spec() -> Tuple[Var[Dict[str, Any]]]: ...
+def on_submit_string_event_spec() -> Tuple[Var[Dict[str, str]]]: ...
+
class Form(BaseHTML):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- accept: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ accept: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
accept_charset: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- action: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ action: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_complete: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- enc_type: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- method: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- name: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- no_validate: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- target: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ enc_type: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ method: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ name: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ no_validate: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ target: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
reset_on_submit: Optional[Union[Var[bool], bool]] = None,
handle_submit_unique_name: Optional[Union[Var[str], str]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
on_submit: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
+ Union[EventType[Dict[str, Any]], EventType[Dict[str, str]]]
] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Form":
"""Create a form component.
@@ -553,6 +359,7 @@ class Form(BaseHTML):
target: Where to display the response after submitting the form
reset_on_submit: If true, the form will be cleared after submit.
handle_submit_unique_name: The name used to make this form's submit handler function unique.
+ on_submit: Fired when the form is submitted
access_key: Provides a hint for generating a keyboard shortcut for the current element.
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
content_editable: Indicates whether the element's content is editable.
@@ -582,189 +389,103 @@ class Form(BaseHTML):
"""
...
+ def add_imports(self) -> ImportDict: ...
+ def add_hooks(self) -> list[str]: ...
+
class Input(BaseHTML):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- accept: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- alt: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
+ accept: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ alt: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_complete: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- auto_focus: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- capture: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- checked: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ auto_focus: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ capture: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ checked: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
default_checked: Optional[Union[Var[bool], bool]] = None,
default_value: Optional[Union[Var[str], str]] = None,
- dirname: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- disabled: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- form: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- form_action: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ dirname: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ disabled: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ form: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ form_action: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
form_enc_type: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- form_method: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ form_method: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
form_no_validate: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- form_target: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- list: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- max: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- max_length: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- min_length: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- min: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- multiple: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- name: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- pattern: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- placeholder: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- read_only: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- required: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- size: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- src: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- step: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- type: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- use_map: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- value: Optional[
- Union[Var[Union[str, int, float]], Union[str, int, float]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ form_target: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ list: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ max: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ max_length: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ min_length: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ min: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ multiple: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ name: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ pattern: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ placeholder: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ read_only: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ required: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ size: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ src: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ step: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ type: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ use_map: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ value: Optional[Union[Var[Union[float, int, str]], float, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_key_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_key_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[str]] = None,
+ on_change: Optional[EventType[str]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[str]] = None,
+ on_key_down: Optional[EventType[str]] = None,
+ on_key_up: Optional[EventType[str]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Input":
"""Create the component.
@@ -803,6 +524,11 @@ class Input(BaseHTML):
type: Specifies the type of input
use_map: Name of the image map used with the input
value: Value of the input
+ on_change: Fired when the input value changes
+ on_focus: Fired when the input gains focus
+ on_blur: Fired when the input loses focus
+ on_key_down: Fired when a key is pressed down
+ on_key_up: Fired when a key is released
access_key: Provides a hint for generating a keyboard shortcut for the current element.
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
content_editable: Indicates whether the element's content is editable.
@@ -838,102 +564,54 @@ class Label(BaseHTML):
def create( # type: ignore
cls,
*children,
- html_for: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- form: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ html_for: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ form: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Label":
"""Create the component.
@@ -976,98 +654,52 @@ class Legend(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Legend":
"""Create the component.
@@ -1108,109 +740,59 @@ class Meter(BaseHTML):
def create( # type: ignore
cls,
*children,
- form: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- high: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- low: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- max: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- min: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- optimum: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- value: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ form: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ high: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ low: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ max: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ min: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ optimum: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ value: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Meter":
"""Create the component.
@@ -1258,104 +840,54 @@ class Optgroup(BaseHTML):
def create( # type: ignore
cls,
*children,
- disabled: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- label: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ disabled: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ label: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Optgroup":
"""Create the component.
@@ -1398,110 +930,56 @@ class Option(BaseHTML):
def create( # type: ignore
cls,
*children,
- disabled: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- label: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- selected: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- value: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ disabled: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ label: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ selected: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ value: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Option":
"""Create the component.
@@ -1546,103 +1024,55 @@ class Output(BaseHTML):
def create( # type: ignore
cls,
*children,
- html_for: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- form: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- name: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ html_for: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ form: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ name: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Output":
"""Create the component.
@@ -1686,103 +1116,55 @@ class Progress(BaseHTML):
def create( # type: ignore
cls,
*children,
- form: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- max: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- value: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ form: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ max: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ value: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Progress":
"""Create the component.
@@ -1821,125 +1203,68 @@ class Progress(BaseHTML):
...
class Select(BaseHTML):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
auto_complete: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- auto_focus: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- disabled: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- form: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- multiple: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- name: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- required: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- size: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ auto_focus: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ disabled: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ form: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ multiple: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ name: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ required: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ size: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_change: Optional[EventType[str]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Select":
"""Create the component.
@@ -1953,6 +1278,7 @@ class Select(BaseHTML):
name: Name of the select, used when submitting the form
required: Indicates that the select control must have a selected option
size: Number of visible options in a drop-down list
+ on_change: Fired when the select value changes
access_key: Provides a hint for generating a keyboard shortcut for the current element.
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
content_editable: Indicates whether the element's content is editable.
@@ -1982,159 +1308,88 @@ class Select(BaseHTML):
"""
...
-AUTO_HEIGHT_JS = '\nconst autoHeightOnInput = (e, is_enabled) => {\n if (is_enabled) {\n const el = e.target;\n el.style.overflowY = "hidden";\n el.style.height = "auto";\n el.style.height = (e.target.scrollHeight) + "px";\n if (el.form && !el.form.data_resize_on_reset) {\n el.form.addEventListener("reset", () => window.setTimeout(() => autoHeightOnInput(e, is_enabled), 0))\n el.form.data_resize_on_reset = true;\n }\n }\n}\n'
+AUTO_HEIGHT_JS = '\nconst autoHeightOnInput = (e, is_enabled) => {\n if (is_enabled) {\n const el = e.target;\n el.style.overflowY = "scroll";\n el.style.height = "auto";\n el.style.height = (e.target.scrollHeight) + "px";\n if (el.form && !el.form.data_resize_on_reset) {\n el.form.addEventListener("reset", () => window.setTimeout(() => autoHeightOnInput(e, is_enabled), 0))\n el.form.data_resize_on_reset = true;\n }\n }\n}\n'
ENTER_KEY_SUBMIT_JS = "\nconst enterKeySubmitOnKeyDown = (e, is_enabled) => {\n if (is_enabled && e.which === 13 && !e.shiftKey) {\n e.preventDefault();\n if (!e.repeat) {\n if (e.target.form) {\n e.target.form.requestSubmit();\n }\n }\n }\n}\n"
class Textarea(BaseHTML):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
auto_complete: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- auto_focus: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ auto_focus: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_height: Optional[Union[Var[bool], bool]] = None,
- cols: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- dirname: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- disabled: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ cols: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ dirname: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ disabled: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_submit: Optional[Union[Var[bool], bool]] = None,
- form: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- max_length: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- min_length: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- name: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- placeholder: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- read_only: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- required: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- rows: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- value: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- wrap: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ form: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ max_length: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ min_length: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ name: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ placeholder: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ read_only: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ required: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ rows: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ value: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ wrap: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_key_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_key_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[str]] = None,
+ on_change: Optional[EventType[str]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[str]] = None,
+ on_key_down: Optional[EventType[str]] = None,
+ on_key_up: Optional[EventType[str]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Textarea":
- """Create the component.
+ """Create a textarea component.
Args:
- *children: The children of the component.
+ *children: The children of the textarea.
auto_complete: Whether the form control should have autocomplete enabled
auto_focus: Automatically focuses the textarea when the page loads
auto_height: Automatically fit the content height to the text (use min-height with this prop)
@@ -2152,6 +1407,11 @@ class Textarea(BaseHTML):
rows: Visible number of lines in the text control
value: The controlled value of the textarea, read only unless used with on_change
wrap: How the text in the textarea is to be wrapped when submitting the form
+ on_change: Fired when the input value changes
+ on_focus: Fired when the input gains focus
+ on_blur: Fired when the input loses focus
+ on_key_down: Fired when a key is pressed down
+ on_key_up: Fired when a key is released
access_key: Provides a hint for generating a keyboard shortcut for the current element.
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
content_editable: Indicates whether the element's content is editable.
@@ -2174,9 +1434,26 @@ class Textarea(BaseHTML):
class_name: The class name for the component.
autofocus: Whether the component should take the focus once the page is loaded
custom_attrs: custom attribute
- **props: The props of the component.
+ **props: The properties of the textarea.
Returns:
- The component.
+ The textarea component.
+
+ Raises:
+ ValueError: when `enter_key_submit` is combined with `on_key_down`.
"""
...
+
+button = Button.create
+fieldset = Fieldset.create
+form = Form.create
+input = Input.create
+label = Label.create
+legend = Legend.create
+meter = Meter.create
+optgroup = Optgroup.create
+option = Option.create
+output = Output.create
+progress = Progress.create
+select = Select.create
+textarea = Textarea.create
diff --git a/reflex/components/el/elements/inline.py b/reflex/components/el/elements/inline.py
index a8454217b..d1bdf6b87 100644
--- a/reflex/components/el/elements/inline.py
+++ b/reflex/components/el/elements/inline.py
@@ -1,7 +1,8 @@
"""Element classes. This is an auto-generated file. Do not edit. See ../generate.py."""
+
from typing import Union
-from reflex.vars import Var
+from reflex.vars.base import Var
from .base import BaseHTML
@@ -208,3 +209,33 @@ class Wbr(BaseHTML):
"""Display the wbr element."""
tag = "wbr"
+
+
+a = A.create
+abbr = Abbr.create
+b = B.create
+bdi = Bdi.create
+bdo = Bdo.create
+br = Br.create
+cite = Cite.create
+code = Code.create
+data = Data.create
+dfn = Dfn.create
+em = Em.create
+i = I.create
+kbd = Kbd.create
+mark = Mark.create
+q = Q.create
+rp = Rp.create
+rt = Rt.create
+ruby = Ruby.create
+s = S.create
+samp = Samp.create
+small = Small.create
+span = Span.create
+strong = Strong.create
+sub = Sub.create
+sup = Sup.create
+time = Time.create
+u = U.create
+wbr = Wbr.create
diff --git a/reflex/components/el/elements/inline.pyi b/reflex/components/el/elements/inline.pyi
index a18f86243..336e4d3de 100644
--- a/reflex/components/el/elements/inline.pyi
+++ b/reflex/components/el/elements/inline.pyi
@@ -1,14 +1,14 @@
"""Stub file for reflex/components/el/elements/inline.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+from reflex.event import EventType
from reflex.style import Style
-from typing import Union
-from reflex.vars import Var
+from reflex.vars.base import Var
+
from .base import BaseHTML
class A(BaseHTML):
@@ -17,119 +17,63 @@ class A(BaseHTML):
def create( # type: ignore
cls,
*children,
- download: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- href: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- href_lang: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- media: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- ping: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
+ download: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ href: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ href_lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ media: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ ping: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
referrer_policy: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- rel: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- shape: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- target: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ rel: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ shape: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ target: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "A":
"""Create the component.
@@ -179,98 +123,52 @@ class Abbr(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Abbr":
"""Create the component.
@@ -311,98 +209,52 @@ class B(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "B":
"""Create the component.
@@ -443,98 +295,52 @@ class Bdi(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Bdi":
"""Create the component.
@@ -575,98 +381,52 @@ class Bdo(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Bdo":
"""Create the component.
@@ -707,98 +467,52 @@ class Br(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Br":
"""Create the component.
@@ -839,98 +553,52 @@ class Cite(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Cite":
"""Create the component.
@@ -971,98 +639,52 @@ class Code(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Code":
"""Create the component.
@@ -1103,101 +725,53 @@ class Data(BaseHTML):
def create( # type: ignore
cls,
*children,
- value: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ value: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Data":
"""Create the component.
@@ -1239,98 +813,52 @@ class Dfn(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Dfn":
"""Create the component.
@@ -1371,98 +899,52 @@ class Em(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Em":
"""Create the component.
@@ -1503,98 +985,52 @@ class I(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "I":
"""Create the component.
@@ -1635,98 +1071,52 @@ class Kbd(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Kbd":
"""Create the component.
@@ -1767,98 +1157,52 @@ class Mark(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Mark":
"""Create the component.
@@ -1899,99 +1243,53 @@ class Q(BaseHTML):
def create( # type: ignore
cls,
*children,
- cite: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ cite: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Q":
"""Create the component.
@@ -2033,98 +1331,52 @@ class Rp(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Rp":
"""Create the component.
@@ -2165,98 +1417,52 @@ class Rt(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Rt":
"""Create the component.
@@ -2297,98 +1503,52 @@ class Ruby(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Ruby":
"""Create the component.
@@ -2429,98 +1589,52 @@ class S(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "S":
"""Create the component.
@@ -2561,98 +1675,52 @@ class Samp(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Samp":
"""Create the component.
@@ -2693,98 +1761,52 @@ class Small(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Small":
"""Create the component.
@@ -2825,98 +1847,52 @@ class Span(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Span":
"""Create the component.
@@ -2957,98 +1933,52 @@ class Strong(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Strong":
"""Create the component.
@@ -3089,98 +2019,52 @@ class Sub(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Sub":
"""Create the component.
@@ -3221,98 +2105,52 @@ class Sup(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Sup":
"""Create the component.
@@ -3353,101 +2191,53 @@ class Time(BaseHTML):
def create( # type: ignore
cls,
*children,
- date_time: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ date_time: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Time":
"""Create the component.
@@ -3489,98 +2279,52 @@ class U(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "U":
"""Create the component.
@@ -3621,98 +2365,52 @@ class Wbr(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Wbr":
"""Create the component.
@@ -3746,3 +2444,32 @@ class Wbr(BaseHTML):
The component.
"""
...
+
+a = A.create
+abbr = Abbr.create
+b = B.create
+bdi = Bdi.create
+bdo = Bdo.create
+br = Br.create
+cite = Cite.create
+code = Code.create
+data = Data.create
+dfn = Dfn.create
+em = Em.create
+i = I.create
+kbd = Kbd.create
+mark = Mark.create
+q = Q.create
+rp = Rp.create
+rt = Rt.create
+ruby = Ruby.create
+s = S.create
+samp = Samp.create
+small = Small.create
+span = Span.create
+strong = Strong.create
+sub = Sub.create
+sup = Sup.create
+time = Time.create
+u = U.create
+wbr = Wbr.create
diff --git a/reflex/components/el/elements/media.py b/reflex/components/el/elements/media.py
index 2865ca66a..9935902ad 100644
--- a/reflex/components/el/elements/media.py
+++ b/reflex/components/el/elements/media.py
@@ -1,7 +1,10 @@
"""Element classes. This is an auto-generated file. Do not edit. See ../generate.py."""
+
from typing import Any, Union
-from reflex.vars import Var as Var
+from reflex import Component, ComponentNamespace
+from reflex.constants.colors import Color
+from reflex.vars.base import Var
from .base import BaseHTML
@@ -116,6 +119,24 @@ class Img(BaseHTML):
# The name of the map to use with the image
use_map: Var[Union[str, int, bool]]
+ @classmethod
+ def create(cls, *children, **props) -> Component:
+ """Override create method to apply source attribute to value if user fails to pass in attribute.
+
+ Args:
+ *children: The children of the component.
+ **props: The props of the component.
+
+ Returns:
+ The component.
+
+ """
+ return (
+ super().create(src=children[0], **props)
+ if children
+ else super().create(*children, **props)
+ )
+
class Map(BaseHTML):
"""Display the map element."""
@@ -288,6 +309,189 @@ class Svg(BaseHTML):
"""Display the svg element."""
tag = "svg"
+ # The width of the svg.
+ width: Var[Union[str, int]]
+ # The height of the svg.
+ height: Var[Union[str, int]]
+ # The XML namespace declaration.
+ xmlns: Var[str]
+
+
+class Text(BaseHTML):
+ """The SVG text component."""
+
+ tag = "text"
+ # The x coordinate of the starting point of the text baseline.
+ x: Var[Union[str, int]]
+ # The y coordinate of the starting point of the text baseline.
+ y: Var[Union[str, int]]
+ # Shifts the text position horizontally from a previous text element.
+ dx: Var[Union[str, int]]
+ # Shifts the text position vertically from a previous text element.
+ dy: Var[Union[str, int]]
+ # Rotates orientation of each individual glyph.
+ rotate: Var[Union[str, int]]
+ # How the text is stretched or compressed to fit the width defined by the text_length attribute.
+ length_adjust: Var[str]
+ # A width that the text should be scaled to fit.
+ text_length: Var[Union[str, int]]
+
+
+class Line(BaseHTML):
+ """The SVG line component."""
+
+ tag = "line"
+ # The x-axis coordinate of the line starting point.
+ x1: Var[Union[str, int]]
+ # The x-axis coordinate of the the line ending point.
+ x2: Var[Union[str, int]]
+ # The y-axis coordinate of the line starting point.
+ y1: Var[Union[str, int]]
+ # The y-axis coordinate of the the line ending point.
+ y2: Var[Union[str, int]]
+ # The total path length, in user units.
+ path_length: Var[int]
+
+
+class Circle(BaseHTML):
+ """The SVG circle component."""
+
+ tag = "circle"
+ # The x-axis coordinate of the center of the circle.
+ cx: Var[Union[str, int]]
+ # The y-axis coordinate of the center of the circle.
+ cy: Var[Union[str, int]]
+ # The radius of the circle.
+ r: Var[Union[str, int]]
+ # The total length for the circle's circumference, in user units.
+ path_length: Var[int]
+
+
+class Ellipse(BaseHTML):
+ """The SVG ellipse component."""
+
+ tag = "ellipse"
+ # The x position of the center of the ellipse.
+ cx: Var[Union[str, int]]
+ # The y position of the center of the ellipse.
+ cy: Var[Union[str, int]]
+ # The radius of the ellipse on the x axis.
+ rx: Var[Union[str, int]]
+ # The radius of the ellipse on the y axis.
+ ry: Var[Union[str, int]]
+ # The total length for the ellipse's circumference, in user units.
+ path_length: Var[int]
+
+
+class Rect(BaseHTML):
+ """The SVG rect component."""
+
+ tag = "rect"
+ # The x coordinate of the rect.
+ x: Var[Union[str, int]]
+ # The y coordinate of the rect.
+ y: Var[Union[str, int]]
+ # The width of the rect
+ width: Var[Union[str, int]]
+ # The height of the rect.
+ height: Var[Union[str, int]]
+ # The horizontal corner radius of the rect. Defaults to ry if it is specified.
+ rx: Var[Union[str, int]]
+ # The vertical corner radius of the rect. Defaults to rx if it is specified.
+ ry: Var[Union[str, int]]
+ # The total length of the rectangle's perimeter, in user units.
+ path_length: Var[int]
+
+
+class Polygon(BaseHTML):
+ """The SVG polygon component."""
+
+ tag = "polygon"
+ # defines the list of points (pairs of x,y absolute coordinates) required to draw the polygon.
+ points: Var[str]
+ # This prop lets specify the total length for the path, in user units.
+ path_length: Var[int]
+
+
+class Defs(BaseHTML):
+ """Display the defs element."""
+
+ tag = "defs"
+
+
+class LinearGradient(BaseHTML):
+ """Display the linearGradient element."""
+
+ tag = "linearGradient"
+
+ # Units for the gradient.
+ gradient_units: Var[Union[str, bool]]
+
+ # Transform applied to the gradient.
+ gradient_transform: Var[Union[str, bool]]
+
+ # Method used to spread the gradient.
+ spread_method: Var[Union[str, bool]]
+
+ # X coordinate of the starting point of the gradient.
+ x1: Var[Union[str, int, bool]]
+
+ # X coordinate of the ending point of the gradient.
+ x2: Var[Union[str, int, bool]]
+
+ # Y coordinate of the starting point of the gradient.
+ y1: Var[Union[str, int, bool]]
+
+ # Y coordinate of the ending point of the gradient.
+ y2: Var[Union[str, int, bool]]
+
+
+class RadialGradient(BaseHTML):
+ """Display the radialGradient element."""
+
+ tag = "radialGradient"
+
+ # The x coordinate of the end circle of the radial gradient.
+ cx: Var[Union[str, int, bool]]
+
+ # The y coordinate of the end circle of the radial gradient.
+ cy: Var[Union[str, int, bool]]
+
+ # The radius of the start circle of the radial gradient.
+ fr: Var[Union[str, int, bool]]
+
+ # The x coordinate of the start circle of the radial gradient.
+ fx: Var[Union[str, int, bool]]
+
+ # The y coordinate of the start circle of the radial gradient.
+ fy: Var[Union[str, int, bool]]
+
+ # Units for the gradient.
+ gradient_units: Var[Union[str, bool]]
+
+ # Transform applied to the gradient.
+ gradient_transform: Var[Union[str, bool]]
+
+ # The radius of the end circle of the radial gradient.
+ r: Var[Union[str, int, bool]]
+
+ # Method used to spread the gradient.
+ spread_method: Var[Union[str, bool]]
+
+
+class Stop(BaseHTML):
+ """Display the stop element."""
+
+ tag = "stop"
+
+ # Offset of the gradient stop.
+ offset: Var[Union[str, float, int]]
+
+ # Color of the gradient stop.
+ stop_color: Var[Union[str, Color, bool]]
+
+ # Opacity of the gradient stop.
+ stop_opacity: Var[Union[str, float, int, bool]]
class Path(BaseHTML):
@@ -295,5 +499,37 @@ class Path(BaseHTML):
tag = "path"
- # Defines the shape of the path
+ # Defines the shape of the path.
d: Var[Union[str, int, bool]]
+
+
+class SVG(ComponentNamespace):
+ """SVG component namespace."""
+
+ text = staticmethod(Text.create)
+ line = staticmethod(Line.create)
+ circle = staticmethod(Circle.create)
+ ellipse = staticmethod(Ellipse.create)
+ rect = staticmethod(Rect.create)
+ polygon = staticmethod(Polygon.create)
+ path = staticmethod(Path.create)
+ stop = staticmethod(Stop.create)
+ linear_gradient = staticmethod(LinearGradient.create)
+ radial_gradient = staticmethod(RadialGradient.create)
+ defs = staticmethod(Defs.create)
+ __call__ = staticmethod(Svg.create)
+
+
+area = Area.create
+audio = Audio.create
+image = img = Img.create
+map = Map.create
+track = Track.create
+video = Video.create
+embed = Embed.create
+iframe = Iframe.create
+object = Object.create
+picture = Picture.create
+portal = Portal.create
+source = Source.create
+svg = SVG()
diff --git a/reflex/components/el/elements/media.pyi b/reflex/components/el/elements/media.pyi
index d1aa40978..382f3c79c 100644
--- a/reflex/components/el/elements/media.pyi
+++ b/reflex/components/el/elements/media.pyi
@@ -1,14 +1,16 @@
"""Stub file for reflex/components/el/elements/media.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+from reflex import ComponentNamespace
+from reflex.constants.colors import Color
+from reflex.event import EventType
from reflex.style import Style
-from typing import Any, Union
-from reflex.vars import Var as Var
+from reflex.vars.base import Var
+
from .base import BaseHTML
class Area(BaseHTML):
@@ -17,123 +19,65 @@ class Area(BaseHTML):
def create( # type: ignore
cls,
*children,
- alt: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- coords: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- download: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- href: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- href_lang: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- media: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- ping: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
+ alt: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ coords: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ download: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ href: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ href_lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ media: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ ping: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
referrer_policy: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- rel: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- shape: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- target: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ rel: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ shape: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ target: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Area":
"""Create the component.
@@ -185,118 +129,62 @@ class Audio(BaseHTML):
def create( # type: ignore
cls,
*children,
- auto_play: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- buffered: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- controls: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ auto_play: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ buffered: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ controls: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
cross_origin: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- loop: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- muted: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- preload: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- src: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ loop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ muted: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ preload: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ src: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Audio":
"""Create the component.
@@ -345,132 +233,72 @@ class Img(BaseHTML):
def create( # type: ignore
cls,
*children,
- align: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- alt: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
+ align: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ alt: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
cross_origin: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- decoding: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ decoding: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
intrinsicsize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- ismap: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- loading: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ ismap: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ loading: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
referrer_policy: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- sizes: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- src: Optional[Union[Var[Any], Any]] = None,
- src_set: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- use_map: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ sizes: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ src: Optional[Union[Any, Var[Any]]] = None,
+ src_set: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ use_map: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Img":
- """Create the component.
+ """Override create method to apply source attribute to value if user fails to pass in attribute.
Args:
*children: The children of the component.
@@ -512,6 +340,7 @@ class Img(BaseHTML):
Returns:
The component.
+
"""
...
@@ -521,99 +350,53 @@ class Map(BaseHTML):
def create( # type: ignore
cls,
*children,
- name: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ name: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Map":
"""Create the component.
@@ -655,109 +438,57 @@ class Track(BaseHTML):
def create( # type: ignore
cls,
*children,
- default: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- kind: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- label: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- src: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- src_lang: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ default: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ kind: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ label: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ src: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ src_lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Track":
"""Create the component.
@@ -803,124 +534,66 @@ class Video(BaseHTML):
def create( # type: ignore
cls,
*children,
- auto_play: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- buffered: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- controls: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ auto_play: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ buffered: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ controls: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
cross_origin: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- loop: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- muted: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ loop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ muted: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
plays_inline: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- poster: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- preload: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- src: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ poster: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ preload: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ src: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Video":
"""Create the component.
@@ -971,100 +644,54 @@ class Embed(BaseHTML):
def create( # type: ignore
cls,
*children,
- src: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- type: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ src: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ type: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Embed":
"""Create the component.
@@ -1107,119 +734,63 @@ class Iframe(BaseHTML):
def create( # type: ignore
cls,
*children,
- align: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- allow: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- csp: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- loading: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- name: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
+ align: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ allow: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ csp: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ loading: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ name: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
referrer_policy: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- sandbox: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- src: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- src_doc: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ sandbox: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ src: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ src_doc: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Iframe":
"""Create the component.
@@ -1269,105 +840,57 @@ class Object(BaseHTML):
def create( # type: ignore
cls,
*children,
- data: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- form: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- name: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- type: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- use_map: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ data: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ form: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ name: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ type: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ use_map: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Object":
"""Create the component.
@@ -1413,98 +936,52 @@ class Picture(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Picture":
"""Create the component.
@@ -1545,98 +1022,52 @@ class Portal(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Portal":
"""Create the component.
@@ -1677,109 +1108,57 @@ class Source(BaseHTML):
def create( # type: ignore
cls,
*children,
- media: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- sizes: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- src: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- src_set: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- type: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ media: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ sizes: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ src: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ src_set: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ type: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Source":
"""Create the component.
@@ -1825,103 +1204,1025 @@ class Svg(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ width: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ height: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ xmlns: Optional[Union[Var[str], str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Svg":
"""Create the component.
Args:
*children: The children of the component.
+ width: The width of the svg.
+ height: The height of the svg.
+ xmlns: The XML namespace declaration.
+ access_key: Provides a hint for generating a keyboard shortcut for the current element.
+ auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
+ content_editable: Indicates whether the element's content is editable.
+ context_menu: Defines the ID of a
element which will serve as the element's context menu.
+ dir: Defines the text direction. Allowed values are ltr (Left-To-Right) or rtl (Right-To-Left)
+ draggable: Defines whether the element can be dragged.
+ enter_key_hint: Hints what media types the media element is able to play.
+ hidden: Defines whether the element is hidden.
+ input_mode: Defines the type of the element.
+ item_prop: Defines the name of the element for metadata purposes.
+ lang: Defines the language used in the element.
+ role: Defines the role of the element.
+ slot: Assigns a slot in a shadow DOM shadow tree to an element.
+ spell_check: Defines whether the element may be checked for spelling errors.
+ tab_index: Defines the position of the current element in the tabbing order.
+ title: Defines a tooltip for the element.
+ style: The style of the component.
+ key: A unique key for the component.
+ id: The id for the component.
+ class_name: The class name for the component.
+ autofocus: Whether the component should take the focus once the page is loaded
+ custom_attrs: custom attribute
+ **props: The props of the component.
+
+ Returns:
+ The component.
+ """
+ ...
+
+class Text(BaseHTML):
+ @overload
+ @classmethod
+ def create( # type: ignore
+ cls,
+ *children,
+ x: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ y: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ dx: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ dy: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ rotate: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ length_adjust: Optional[Union[Var[str], str]] = None,
+ text_length: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ auto_capitalize: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ content_editable: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ context_menu: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ enter_key_hint: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ style: Optional[Style] = None,
+ key: Optional[Any] = None,
+ id: Optional[Any] = None,
+ class_name: Optional[Any] = None,
+ autofocus: Optional[bool] = None,
+ custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
+ ) -> "Text":
+ """Create the component.
+
+ Args:
+ *children: The children of the component.
+ x: The x coordinate of the starting point of the text baseline.
+ y: The y coordinate of the starting point of the text baseline.
+ dx: Shifts the text position horizontally from a previous text element.
+ dy: Shifts the text position vertically from a previous text element.
+ rotate: Rotates orientation of each individual glyph.
+ length_adjust: How the text is stretched or compressed to fit the width defined by the text_length attribute.
+ text_length: A width that the text should be scaled to fit.
+ access_key: Provides a hint for generating a keyboard shortcut for the current element.
+ auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
+ content_editable: Indicates whether the element's content is editable.
+ context_menu: Defines the ID of a element which will serve as the element's context menu.
+ dir: Defines the text direction. Allowed values are ltr (Left-To-Right) or rtl (Right-To-Left)
+ draggable: Defines whether the element can be dragged.
+ enter_key_hint: Hints what media types the media element is able to play.
+ hidden: Defines whether the element is hidden.
+ input_mode: Defines the type of the element.
+ item_prop: Defines the name of the element for metadata purposes.
+ lang: Defines the language used in the element.
+ role: Defines the role of the element.
+ slot: Assigns a slot in a shadow DOM shadow tree to an element.
+ spell_check: Defines whether the element may be checked for spelling errors.
+ tab_index: Defines the position of the current element in the tabbing order.
+ title: Defines a tooltip for the element.
+ style: The style of the component.
+ key: A unique key for the component.
+ id: The id for the component.
+ class_name: The class name for the component.
+ autofocus: Whether the component should take the focus once the page is loaded
+ custom_attrs: custom attribute
+ **props: The props of the component.
+
+ Returns:
+ The component.
+ """
+ ...
+
+class Line(BaseHTML):
+ @overload
+ @classmethod
+ def create( # type: ignore
+ cls,
+ *children,
+ x1: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ x2: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ y1: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ y2: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ path_length: Optional[Union[Var[int], int]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ auto_capitalize: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ content_editable: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ context_menu: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ enter_key_hint: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ style: Optional[Style] = None,
+ key: Optional[Any] = None,
+ id: Optional[Any] = None,
+ class_name: Optional[Any] = None,
+ autofocus: Optional[bool] = None,
+ custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
+ ) -> "Line":
+ """Create the component.
+
+ Args:
+ *children: The children of the component.
+ x1: The x-axis coordinate of the line starting point.
+ x2: The x-axis coordinate of the the line ending point.
+ y1: The y-axis coordinate of the line starting point.
+ y2: The y-axis coordinate of the the line ending point.
+ path_length: The total path length, in user units.
+ access_key: Provides a hint for generating a keyboard shortcut for the current element.
+ auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
+ content_editable: Indicates whether the element's content is editable.
+ context_menu: Defines the ID of a element which will serve as the element's context menu.
+ dir: Defines the text direction. Allowed values are ltr (Left-To-Right) or rtl (Right-To-Left)
+ draggable: Defines whether the element can be dragged.
+ enter_key_hint: Hints what media types the media element is able to play.
+ hidden: Defines whether the element is hidden.
+ input_mode: Defines the type of the element.
+ item_prop: Defines the name of the element for metadata purposes.
+ lang: Defines the language used in the element.
+ role: Defines the role of the element.
+ slot: Assigns a slot in a shadow DOM shadow tree to an element.
+ spell_check: Defines whether the element may be checked for spelling errors.
+ tab_index: Defines the position of the current element in the tabbing order.
+ title: Defines a tooltip for the element.
+ style: The style of the component.
+ key: A unique key for the component.
+ id: The id for the component.
+ class_name: The class name for the component.
+ autofocus: Whether the component should take the focus once the page is loaded
+ custom_attrs: custom attribute
+ **props: The props of the component.
+
+ Returns:
+ The component.
+ """
+ ...
+
+class Circle(BaseHTML):
+ @overload
+ @classmethod
+ def create( # type: ignore
+ cls,
+ *children,
+ cx: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ cy: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ r: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ path_length: Optional[Union[Var[int], int]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ auto_capitalize: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ content_editable: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ context_menu: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ enter_key_hint: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ style: Optional[Style] = None,
+ key: Optional[Any] = None,
+ id: Optional[Any] = None,
+ class_name: Optional[Any] = None,
+ autofocus: Optional[bool] = None,
+ custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
+ ) -> "Circle":
+ """Create the component.
+
+ Args:
+ *children: The children of the component.
+ cx: The x-axis coordinate of the center of the circle.
+ cy: The y-axis coordinate of the center of the circle.
+ r: The radius of the circle.
+ path_length: The total length for the circle's circumference, in user units.
+ access_key: Provides a hint for generating a keyboard shortcut for the current element.
+ auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
+ content_editable: Indicates whether the element's content is editable.
+ context_menu: Defines the ID of a element which will serve as the element's context menu.
+ dir: Defines the text direction. Allowed values are ltr (Left-To-Right) or rtl (Right-To-Left)
+ draggable: Defines whether the element can be dragged.
+ enter_key_hint: Hints what media types the media element is able to play.
+ hidden: Defines whether the element is hidden.
+ input_mode: Defines the type of the element.
+ item_prop: Defines the name of the element for metadata purposes.
+ lang: Defines the language used in the element.
+ role: Defines the role of the element.
+ slot: Assigns a slot in a shadow DOM shadow tree to an element.
+ spell_check: Defines whether the element may be checked for spelling errors.
+ tab_index: Defines the position of the current element in the tabbing order.
+ title: Defines a tooltip for the element.
+ style: The style of the component.
+ key: A unique key for the component.
+ id: The id for the component.
+ class_name: The class name for the component.
+ autofocus: Whether the component should take the focus once the page is loaded
+ custom_attrs: custom attribute
+ **props: The props of the component.
+
+ Returns:
+ The component.
+ """
+ ...
+
+class Ellipse(BaseHTML):
+ @overload
+ @classmethod
+ def create( # type: ignore
+ cls,
+ *children,
+ cx: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ cy: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ rx: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ ry: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ path_length: Optional[Union[Var[int], int]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ auto_capitalize: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ content_editable: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ context_menu: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ enter_key_hint: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ style: Optional[Style] = None,
+ key: Optional[Any] = None,
+ id: Optional[Any] = None,
+ class_name: Optional[Any] = None,
+ autofocus: Optional[bool] = None,
+ custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
+ ) -> "Ellipse":
+ """Create the component.
+
+ Args:
+ *children: The children of the component.
+ cx: The x position of the center of the ellipse.
+ cy: The y position of the center of the ellipse.
+ rx: The radius of the ellipse on the x axis.
+ ry: The radius of the ellipse on the y axis.
+ path_length: The total length for the ellipse's circumference, in user units.
+ access_key: Provides a hint for generating a keyboard shortcut for the current element.
+ auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
+ content_editable: Indicates whether the element's content is editable.
+ context_menu: Defines the ID of a element which will serve as the element's context menu.
+ dir: Defines the text direction. Allowed values are ltr (Left-To-Right) or rtl (Right-To-Left)
+ draggable: Defines whether the element can be dragged.
+ enter_key_hint: Hints what media types the media element is able to play.
+ hidden: Defines whether the element is hidden.
+ input_mode: Defines the type of the element.
+ item_prop: Defines the name of the element for metadata purposes.
+ lang: Defines the language used in the element.
+ role: Defines the role of the element.
+ slot: Assigns a slot in a shadow DOM shadow tree to an element.
+ spell_check: Defines whether the element may be checked for spelling errors.
+ tab_index: Defines the position of the current element in the tabbing order.
+ title: Defines a tooltip for the element.
+ style: The style of the component.
+ key: A unique key for the component.
+ id: The id for the component.
+ class_name: The class name for the component.
+ autofocus: Whether the component should take the focus once the page is loaded
+ custom_attrs: custom attribute
+ **props: The props of the component.
+
+ Returns:
+ The component.
+ """
+ ...
+
+class Rect(BaseHTML):
+ @overload
+ @classmethod
+ def create( # type: ignore
+ cls,
+ *children,
+ x: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ y: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ width: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ height: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ rx: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ ry: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ path_length: Optional[Union[Var[int], int]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ auto_capitalize: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ content_editable: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ context_menu: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ enter_key_hint: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ style: Optional[Style] = None,
+ key: Optional[Any] = None,
+ id: Optional[Any] = None,
+ class_name: Optional[Any] = None,
+ autofocus: Optional[bool] = None,
+ custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
+ ) -> "Rect":
+ """Create the component.
+
+ Args:
+ *children: The children of the component.
+ x: The x coordinate of the rect.
+ y: The y coordinate of the rect.
+ width: The width of the rect
+ height: The height of the rect.
+ rx: The horizontal corner radius of the rect. Defaults to ry if it is specified.
+ ry: The vertical corner radius of the rect. Defaults to rx if it is specified.
+ path_length: The total length of the rectangle's perimeter, in user units.
+ access_key: Provides a hint for generating a keyboard shortcut for the current element.
+ auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
+ content_editable: Indicates whether the element's content is editable.
+ context_menu: Defines the ID of a element which will serve as the element's context menu.
+ dir: Defines the text direction. Allowed values are ltr (Left-To-Right) or rtl (Right-To-Left)
+ draggable: Defines whether the element can be dragged.
+ enter_key_hint: Hints what media types the media element is able to play.
+ hidden: Defines whether the element is hidden.
+ input_mode: Defines the type of the element.
+ item_prop: Defines the name of the element for metadata purposes.
+ lang: Defines the language used in the element.
+ role: Defines the role of the element.
+ slot: Assigns a slot in a shadow DOM shadow tree to an element.
+ spell_check: Defines whether the element may be checked for spelling errors.
+ tab_index: Defines the position of the current element in the tabbing order.
+ title: Defines a tooltip for the element.
+ style: The style of the component.
+ key: A unique key for the component.
+ id: The id for the component.
+ class_name: The class name for the component.
+ autofocus: Whether the component should take the focus once the page is loaded
+ custom_attrs: custom attribute
+ **props: The props of the component.
+
+ Returns:
+ The component.
+ """
+ ...
+
+class Polygon(BaseHTML):
+ @overload
+ @classmethod
+ def create( # type: ignore
+ cls,
+ *children,
+ points: Optional[Union[Var[str], str]] = None,
+ path_length: Optional[Union[Var[int], int]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ auto_capitalize: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ content_editable: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ context_menu: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ enter_key_hint: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ style: Optional[Style] = None,
+ key: Optional[Any] = None,
+ id: Optional[Any] = None,
+ class_name: Optional[Any] = None,
+ autofocus: Optional[bool] = None,
+ custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
+ ) -> "Polygon":
+ """Create the component.
+
+ Args:
+ *children: The children of the component.
+ points: defines the list of points (pairs of x,y absolute coordinates) required to draw the polygon.
+ path_length: This prop lets specify the total length for the path, in user units.
+ access_key: Provides a hint for generating a keyboard shortcut for the current element.
+ auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
+ content_editable: Indicates whether the element's content is editable.
+ context_menu: Defines the ID of a element which will serve as the element's context menu.
+ dir: Defines the text direction. Allowed values are ltr (Left-To-Right) or rtl (Right-To-Left)
+ draggable: Defines whether the element can be dragged.
+ enter_key_hint: Hints what media types the media element is able to play.
+ hidden: Defines whether the element is hidden.
+ input_mode: Defines the type of the element.
+ item_prop: Defines the name of the element for metadata purposes.
+ lang: Defines the language used in the element.
+ role: Defines the role of the element.
+ slot: Assigns a slot in a shadow DOM shadow tree to an element.
+ spell_check: Defines whether the element may be checked for spelling errors.
+ tab_index: Defines the position of the current element in the tabbing order.
+ title: Defines a tooltip for the element.
+ style: The style of the component.
+ key: A unique key for the component.
+ id: The id for the component.
+ class_name: The class name for the component.
+ autofocus: Whether the component should take the focus once the page is loaded
+ custom_attrs: custom attribute
+ **props: The props of the component.
+
+ Returns:
+ The component.
+ """
+ ...
+
+class Defs(BaseHTML):
+ @overload
+ @classmethod
+ def create( # type: ignore
+ cls,
+ *children,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ auto_capitalize: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ content_editable: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ context_menu: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ enter_key_hint: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ style: Optional[Style] = None,
+ key: Optional[Any] = None,
+ id: Optional[Any] = None,
+ class_name: Optional[Any] = None,
+ autofocus: Optional[bool] = None,
+ custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
+ ) -> "Defs":
+ """Create the component.
+
+ Args:
+ *children: The children of the component.
+ access_key: Provides a hint for generating a keyboard shortcut for the current element.
+ auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
+ content_editable: Indicates whether the element's content is editable.
+ context_menu: Defines the ID of a element which will serve as the element's context menu.
+ dir: Defines the text direction. Allowed values are ltr (Left-To-Right) or rtl (Right-To-Left)
+ draggable: Defines whether the element can be dragged.
+ enter_key_hint: Hints what media types the media element is able to play.
+ hidden: Defines whether the element is hidden.
+ input_mode: Defines the type of the element.
+ item_prop: Defines the name of the element for metadata purposes.
+ lang: Defines the language used in the element.
+ role: Defines the role of the element.
+ slot: Assigns a slot in a shadow DOM shadow tree to an element.
+ spell_check: Defines whether the element may be checked for spelling errors.
+ tab_index: Defines the position of the current element in the tabbing order.
+ title: Defines a tooltip for the element.
+ style: The style of the component.
+ key: A unique key for the component.
+ id: The id for the component.
+ class_name: The class name for the component.
+ autofocus: Whether the component should take the focus once the page is loaded
+ custom_attrs: custom attribute
+ **props: The props of the component.
+
+ Returns:
+ The component.
+ """
+ ...
+
+class LinearGradient(BaseHTML):
+ @overload
+ @classmethod
+ def create( # type: ignore
+ cls,
+ *children,
+ gradient_units: Optional[Union[Var[Union[bool, str]], bool, str]] = None,
+ gradient_transform: Optional[Union[Var[Union[bool, str]], bool, str]] = None,
+ spread_method: Optional[Union[Var[Union[bool, str]], bool, str]] = None,
+ x1: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ x2: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ y1: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ y2: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ auto_capitalize: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ content_editable: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ context_menu: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ enter_key_hint: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ style: Optional[Style] = None,
+ key: Optional[Any] = None,
+ id: Optional[Any] = None,
+ class_name: Optional[Any] = None,
+ autofocus: Optional[bool] = None,
+ custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
+ ) -> "LinearGradient":
+ """Create the component.
+
+ Args:
+ *children: The children of the component.
+ gradient_units: Units for the gradient.
+ gradient_transform: Transform applied to the gradient.
+ spread_method: Method used to spread the gradient.
+ x1: X coordinate of the starting point of the gradient.
+ x2: X coordinate of the ending point of the gradient.
+ y1: Y coordinate of the starting point of the gradient.
+ y2: Y coordinate of the ending point of the gradient.
+ access_key: Provides a hint for generating a keyboard shortcut for the current element.
+ auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
+ content_editable: Indicates whether the element's content is editable.
+ context_menu: Defines the ID of a element which will serve as the element's context menu.
+ dir: Defines the text direction. Allowed values are ltr (Left-To-Right) or rtl (Right-To-Left)
+ draggable: Defines whether the element can be dragged.
+ enter_key_hint: Hints what media types the media element is able to play.
+ hidden: Defines whether the element is hidden.
+ input_mode: Defines the type of the element.
+ item_prop: Defines the name of the element for metadata purposes.
+ lang: Defines the language used in the element.
+ role: Defines the role of the element.
+ slot: Assigns a slot in a shadow DOM shadow tree to an element.
+ spell_check: Defines whether the element may be checked for spelling errors.
+ tab_index: Defines the position of the current element in the tabbing order.
+ title: Defines a tooltip for the element.
+ style: The style of the component.
+ key: A unique key for the component.
+ id: The id for the component.
+ class_name: The class name for the component.
+ autofocus: Whether the component should take the focus once the page is loaded
+ custom_attrs: custom attribute
+ **props: The props of the component.
+
+ Returns:
+ The component.
+ """
+ ...
+
+class RadialGradient(BaseHTML):
+ @overload
+ @classmethod
+ def create( # type: ignore
+ cls,
+ *children,
+ cx: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ cy: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ fr: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ fx: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ fy: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ gradient_units: Optional[Union[Var[Union[bool, str]], bool, str]] = None,
+ gradient_transform: Optional[Union[Var[Union[bool, str]], bool, str]] = None,
+ r: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spread_method: Optional[Union[Var[Union[bool, str]], bool, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ auto_capitalize: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ content_editable: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ context_menu: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ enter_key_hint: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ style: Optional[Style] = None,
+ key: Optional[Any] = None,
+ id: Optional[Any] = None,
+ class_name: Optional[Any] = None,
+ autofocus: Optional[bool] = None,
+ custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
+ ) -> "RadialGradient":
+ """Create the component.
+
+ Args:
+ *children: The children of the component.
+ cx: The x coordinate of the end circle of the radial gradient.
+ cy: The y coordinate of the end circle of the radial gradient.
+ fr: The radius of the start circle of the radial gradient.
+ fx: The x coordinate of the start circle of the radial gradient.
+ fy: The y coordinate of the start circle of the radial gradient.
+ gradient_units: Units for the gradient.
+ gradient_transform: Transform applied to the gradient.
+ r: The radius of the end circle of the radial gradient.
+ spread_method: Method used to spread the gradient.
+ access_key: Provides a hint for generating a keyboard shortcut for the current element.
+ auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
+ content_editable: Indicates whether the element's content is editable.
+ context_menu: Defines the ID of a element which will serve as the element's context menu.
+ dir: Defines the text direction. Allowed values are ltr (Left-To-Right) or rtl (Right-To-Left)
+ draggable: Defines whether the element can be dragged.
+ enter_key_hint: Hints what media types the media element is able to play.
+ hidden: Defines whether the element is hidden.
+ input_mode: Defines the type of the element.
+ item_prop: Defines the name of the element for metadata purposes.
+ lang: Defines the language used in the element.
+ role: Defines the role of the element.
+ slot: Assigns a slot in a shadow DOM shadow tree to an element.
+ spell_check: Defines whether the element may be checked for spelling errors.
+ tab_index: Defines the position of the current element in the tabbing order.
+ title: Defines a tooltip for the element.
+ style: The style of the component.
+ key: A unique key for the component.
+ id: The id for the component.
+ class_name: The class name for the component.
+ autofocus: Whether the component should take the focus once the page is loaded
+ custom_attrs: custom attribute
+ **props: The props of the component.
+
+ Returns:
+ The component.
+ """
+ ...
+
+class Stop(BaseHTML):
+ @overload
+ @classmethod
+ def create( # type: ignore
+ cls,
+ *children,
+ offset: Optional[Union[Var[Union[float, int, str]], float, int, str]] = None,
+ stop_color: Optional[
+ Union[Color, Var[Union[Color, bool, str]], bool, str]
+ ] = None,
+ stop_opacity: Optional[
+ Union[Var[Union[bool, float, int, str]], bool, float, int, str]
+ ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ auto_capitalize: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ content_editable: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ context_menu: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ enter_key_hint: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ style: Optional[Style] = None,
+ key: Optional[Any] = None,
+ id: Optional[Any] = None,
+ class_name: Optional[Any] = None,
+ autofocus: Optional[bool] = None,
+ custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
+ ) -> "Stop":
+ """Create the component.
+
+ Args:
+ *children: The children of the component.
+ offset: Offset of the gradient stop.
+ stop_color: Color of the gradient stop.
+ stop_opacity: Opacity of the gradient stop.
access_key: Provides a hint for generating a keyboard shortcut for the current element.
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
content_editable: Indicates whether the element's content is editable.
@@ -1957,105 +2258,59 @@ class Path(BaseHTML):
def create( # type: ignore
cls,
*children,
- d: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ d: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Path":
"""Create the component.
Args:
*children: The children of the component.
- d: Defines the shape of the path
+ d: Defines the shape of the path.
access_key: Provides a hint for generating a keyboard shortcut for the current element.
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
content_editable: Indicates whether the element's content is editable.
@@ -2084,3 +2339,119 @@ class Path(BaseHTML):
The component.
"""
...
+
+class SVG(ComponentNamespace):
+ text = staticmethod(Text.create)
+ line = staticmethod(Line.create)
+ circle = staticmethod(Circle.create)
+ ellipse = staticmethod(Ellipse.create)
+ rect = staticmethod(Rect.create)
+ polygon = staticmethod(Polygon.create)
+ path = staticmethod(Path.create)
+ stop = staticmethod(Stop.create)
+ linear_gradient = staticmethod(LinearGradient.create)
+ radial_gradient = staticmethod(RadialGradient.create)
+ defs = staticmethod(Defs.create)
+
+ @staticmethod
+ def __call__(
+ *children,
+ width: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ height: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ xmlns: Optional[Union[Var[str], str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ auto_capitalize: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ content_editable: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ context_menu: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ enter_key_hint: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ style: Optional[Style] = None,
+ key: Optional[Any] = None,
+ id: Optional[Any] = None,
+ class_name: Optional[Any] = None,
+ autofocus: Optional[bool] = None,
+ custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
+ ) -> "Svg":
+ """Create the component.
+
+ Args:
+ *children: The children of the component.
+ width: The width of the svg.
+ height: The height of the svg.
+ xmlns: The XML namespace declaration.
+ access_key: Provides a hint for generating a keyboard shortcut for the current element.
+ auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
+ content_editable: Indicates whether the element's content is editable.
+ context_menu: Defines the ID of a element which will serve as the element's context menu.
+ dir: Defines the text direction. Allowed values are ltr (Left-To-Right) or rtl (Right-To-Left)
+ draggable: Defines whether the element can be dragged.
+ enter_key_hint: Hints what media types the media element is able to play.
+ hidden: Defines whether the element is hidden.
+ input_mode: Defines the type of the element.
+ item_prop: Defines the name of the element for metadata purposes.
+ lang: Defines the language used in the element.
+ role: Defines the role of the element.
+ slot: Assigns a slot in a shadow DOM shadow tree to an element.
+ spell_check: Defines whether the element may be checked for spelling errors.
+ tab_index: Defines the position of the current element in the tabbing order.
+ title: Defines a tooltip for the element.
+ style: The style of the component.
+ key: A unique key for the component.
+ id: The id for the component.
+ class_name: The class name for the component.
+ autofocus: Whether the component should take the focus once the page is loaded
+ custom_attrs: custom attribute
+ **props: The props of the component.
+
+ Returns:
+ The component.
+ """
+ ...
+
+area = Area.create
+audio = Audio.create
+image = img = Img.create
+map = Map.create
+track = Track.create
+video = Video.create
+embed = Embed.create
+iframe = Iframe.create
+object = Object.create
+picture = Picture.create
+portal = Portal.create
+source = Source.create
+svg = SVG()
diff --git a/reflex/components/el/elements/metadata.py b/reflex/components/el/elements/metadata.py
index 2ff25755e..983a8f3a0 100644
--- a/reflex/components/el/elements/metadata.py
+++ b/reflex/components/el/elements/metadata.py
@@ -1,8 +1,9 @@
"""Element classes. This is an auto-generated file. Do not edit. See ../generate.py."""
-from typing import Union
+
+from typing import List, Union
from reflex.components.el.element import Element
-from reflex.vars import Var as Var
+from reflex.vars.base import Var
from .base import BaseHTML
@@ -28,24 +29,49 @@ class Link(BaseHTML): # noqa: E742
tag = "link"
+ # Specifies the CORS settings for the linked resource
cross_origin: Var[Union[str, int, bool]]
+
+ # Specifies the URL of the linked document/resource
href: Var[Union[str, int, bool]]
+
+ # Specifies the language of the text in the linked document
href_lang: Var[Union[str, int, bool]]
+
+ # Allows a browser to check the fetched link for integrity
integrity: Var[Union[str, int, bool]]
+
+ # Specifies on what device the linked document will be displayed
media: Var[Union[str, int, bool]]
+
+ # Specifies the referrer policy of the linked document
referrer_policy: Var[Union[str, int, bool]]
+
+ # Specifies the relationship between the current document and the linked one
rel: Var[Union[str, int, bool]]
+
+ # Specifies the sizes of icons for visual media
sizes: Var[Union[str, int, bool]]
+
+ # Specifies the MIME type of the linked document
type: Var[Union[str, int, bool]]
class Meta(BaseHTML): # Inherits common attributes from BaseHTML
"""Display the meta element."""
- tag = "meta"
+ tag = "meta" # The HTML tag for this element is
+
+ # Specifies the character encoding for the HTML document
char_set: Var[Union[str, int, bool]]
+
+ # Defines the content of the metadata
content: Var[Union[str, int, bool]]
+
+ # Provides an HTTP header for the information/value of the content attribute
http_equiv: Var[Union[str, int, bool]]
+
+ # Specifies a name for the metadata
name: Var[Union[str, int, bool]]
@@ -53,3 +79,22 @@ class Title(Element): # noqa: E742
"""Display the title element."""
tag = "title"
+
+
+# Had to be named with an underscore so it doesnt conflict with reflex.style Style in pyi
+class StyleEl(Element): # noqa: E742
+ """Display the style element."""
+
+ tag = "style"
+
+ media: Var[Union[str, int, bool]]
+
+ special_props: List[Var] = [Var(_js_expr="suppressHydrationWarning")]
+
+
+base = Base.create
+head = Head.create
+link = Link.create
+meta = Meta.create
+title = Title.create
+style = StyleEl.create
diff --git a/reflex/components/el/elements/metadata.pyi b/reflex/components/el/elements/metadata.pyi
index b9e126a6c..498695a80 100644
--- a/reflex/components/el/elements/metadata.pyi
+++ b/reflex/components/el/elements/metadata.pyi
@@ -1,15 +1,15 @@
"""Stub file for reflex/components/el/elements/metadata.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Union
from reflex.components.el.element import Element
-from reflex.vars import Var as Var
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
+
from .base import BaseHTML
class Base(BaseHTML):
@@ -18,102 +18,54 @@ class Base(BaseHTML):
def create( # type: ignore
cls,
*children,
- href: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- target: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ href: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ target: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Base":
"""Create the component.
@@ -154,98 +106,52 @@ class Head(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Head":
"""Create the component.
@@ -287,123 +193,78 @@ class Link(BaseHTML):
cls,
*children,
cross_origin: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- href: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- href_lang: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- integrity: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- media: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ href: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ href_lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ integrity: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ media: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
referrer_policy: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- rel: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- sizes: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- type: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ rel: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ sizes: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ type: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Link":
"""Create the component.
Args:
*children: The children of the component.
+ cross_origin: Specifies the CORS settings for the linked resource
+ href: Specifies the URL of the linked document/resource
+ href_lang: Specifies the language of the text in the linked document
+ integrity: Allows a browser to check the fetched link for integrity
+ media: Specifies on what device the linked document will be displayed
+ referrer_policy: Specifies the referrer policy of the linked document
+ rel: Specifies the relationship between the current document and the linked one
+ sizes: Specifies the sizes of icons for visual media
+ type: Specifies the MIME type of the linked document
access_key: Provides a hint for generating a keyboard shortcut for the current element.
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
content_editable: Indicates whether the element's content is editable.
@@ -439,113 +300,65 @@ class Meta(BaseHTML):
def create( # type: ignore
cls,
*children,
- char_set: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- content: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- http_equiv: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- name: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ char_set: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ content: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ http_equiv: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ name: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Meta":
"""Create the component.
Args:
*children: The children of the component.
+ char_set: Specifies the character encoding for the HTML document
+ content: Defines the content of the metadata
+ http_equiv: Provides an HTTP header for the information/value of the content attribute
+ name: Specifies a name for the metadata
access_key: Provides a hint for generating a keyboard shortcut for the current element.
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
content_editable: Indicates whether the element's content is editable.
@@ -587,52 +400,22 @@ class Title(Element):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Title":
"""Create the component.
@@ -650,3 +433,57 @@ class Title(Element):
The component.
"""
...
+
+class StyleEl(Element):
+ @overload
+ @classmethod
+ def create( # type: ignore
+ cls,
+ *children,
+ media: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ style: Optional[Style] = None,
+ key: Optional[Any] = None,
+ id: Optional[Any] = None,
+ class_name: Optional[Any] = None,
+ autofocus: Optional[bool] = None,
+ custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
+ ) -> "StyleEl":
+ """Create the component.
+
+ Args:
+ *children: The children of the component.
+ style: The style of the component.
+ key: A unique key for the component.
+ id: The id for the component.
+ class_name: The class name for the component.
+ autofocus: Whether the component should take the focus once the page is loaded
+ custom_attrs: custom attribute
+ **props: The props of the component.
+
+ Returns:
+ The component.
+ """
+ ...
+
+base = Base.create
+head = Head.create
+link = Link.create
+meta = Meta.create
+title = Title.create
+style = StyleEl.create
diff --git a/reflex/components/el/elements/other.py b/reflex/components/el/elements/other.py
index 26dbf6050..fa7c6cdec 100644
--- a/reflex/components/el/elements/other.py
+++ b/reflex/components/el/elements/other.py
@@ -1,7 +1,8 @@
"""Element classes. This is an auto-generated file. Do not edit. See ../generate.py."""
+
from typing import Union
-from reflex.vars import Var as Var
+from reflex.vars.base import Var
from .base import BaseHTML
@@ -59,3 +60,12 @@ class Html(BaseHTML):
# Specifies the URL of the document's cache manifest (obsolete in HTML5)
manifest: Var[Union[str, int, bool]]
+
+
+details = Details.create
+dialog = Dialog.create
+summary = Summary.create
+slot = Slot.create
+template = Template.create
+math = Math.create
+html = Html.create
diff --git a/reflex/components/el/elements/other.pyi b/reflex/components/el/elements/other.pyi
index ed89bd745..db884a78b 100644
--- a/reflex/components/el/elements/other.pyi
+++ b/reflex/components/el/elements/other.pyi
@@ -1,14 +1,14 @@
"""Stub file for reflex/components/el/elements/other.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+from reflex.event import EventType
from reflex.style import Style
-from typing import Union
-from reflex.vars import Var as Var
+from reflex.vars.base import Var
+
from .base import BaseHTML
class Details(BaseHTML):
@@ -17,99 +17,53 @@ class Details(BaseHTML):
def create( # type: ignore
cls,
*children,
- open: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ open: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Details":
"""Create the component.
@@ -151,99 +105,53 @@ class Dialog(BaseHTML):
def create( # type: ignore
cls,
*children,
- open: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ open: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Dialog":
"""Create the component.
@@ -285,98 +193,52 @@ class Summary(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Summary":
"""Create the component.
@@ -417,98 +279,52 @@ class Slot(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Slot":
"""Create the component.
@@ -549,98 +365,52 @@ class Template(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Template":
"""Create the component.
@@ -681,98 +451,52 @@ class Math(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Math":
"""Create the component.
@@ -813,101 +537,53 @@ class Html(BaseHTML):
def create( # type: ignore
cls,
*children,
- manifest: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ manifest: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Html":
"""Create the component.
@@ -942,3 +618,11 @@ class Html(BaseHTML):
The component.
"""
...
+
+details = Details.create
+dialog = Dialog.create
+summary = Summary.create
+slot = Slot.create
+template = Template.create
+math = Math.create
+html = Html.create
diff --git a/reflex/components/el/elements/scripts.py b/reflex/components/el/elements/scripts.py
index a37a32494..b53306e02 100644
--- a/reflex/components/el/elements/scripts.py
+++ b/reflex/components/el/elements/scripts.py
@@ -1,7 +1,8 @@
"""Element classes. This is an auto-generated file. Do not edit. See ../generate.py."""
+
from typing import Union
-from reflex.vars import Var as Var
+from reflex.vars.base import Var
from .base import BaseHTML
@@ -50,3 +51,8 @@ class Script(BaseHTML):
# Specifies the MIME type of the script
type: Var[Union[str, int, bool]]
+
+
+canvas = Canvas.create
+noscript = Noscript.create
+script = Script.create
diff --git a/reflex/components/el/elements/scripts.pyi b/reflex/components/el/elements/scripts.pyi
index 79363df76..774fcfc22 100644
--- a/reflex/components/el/elements/scripts.pyi
+++ b/reflex/components/el/elements/scripts.pyi
@@ -1,14 +1,14 @@
"""Stub file for reflex/components/el/elements/scripts.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+from reflex.event import EventType
from reflex.style import Style
-from typing import Union
-from reflex.vars import Var as Var
+from reflex.vars.base import Var
+
from .base import BaseHTML
class Canvas(BaseHTML):
@@ -17,98 +17,52 @@ class Canvas(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Canvas":
"""Create the component.
@@ -149,98 +103,52 @@ class Noscript(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Noscript":
"""Create the component.
@@ -281,121 +189,65 @@ class Script(BaseHTML):
def create( # type: ignore
cls,
*children,
- async_: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- char_set: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ async_: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ char_set: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
cross_origin: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- defer: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- integrity: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- language: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ defer: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ integrity: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ language: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
referrer_policy: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- src: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- type: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ src: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ type: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Script":
"""Create the component.
@@ -438,3 +290,7 @@ class Script(BaseHTML):
The component.
"""
...
+
+canvas = Canvas.create
+noscript = Noscript.create
+script = Script.create
diff --git a/reflex/components/el/elements/sectioning.py b/reflex/components/el/elements/sectioning.py
index ce3549573..6aea8c1e3 100644
--- a/reflex/components/el/elements/sectioning.py
+++ b/reflex/components/el/elements/sectioning.py
@@ -1,7 +1,5 @@
"""Element classes. This is an auto-generated file. Do not edit. See ../generate.py."""
-from reflex.vars import Var as Var
-
from .base import BaseHTML
@@ -93,3 +91,20 @@ class Section(BaseHTML): # noqa: E742
"""Display the section element."""
tag = "section"
+
+
+address = Address.create
+article = Article.create
+aside = Aside.create
+body = Body.create
+header = Header.create
+footer = Footer.create
+h1 = H1.create
+h2 = H2.create
+h3 = H3.create
+h4 = H4.create
+h5 = H5.create
+h6 = H6.create
+main = Main.create
+nav = Nav.create
+section = Section.create
diff --git a/reflex/components/el/elements/sectioning.pyi b/reflex/components/el/elements/sectioning.pyi
index 26f663e66..963d2d651 100644
--- a/reflex/components/el/elements/sectioning.pyi
+++ b/reflex/components/el/elements/sectioning.pyi
@@ -1,13 +1,14 @@
"""Stub file for reflex/components/el/elements/sectioning.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+from reflex.event import EventType
from reflex.style import Style
-from reflex.vars import Var as Var
+from reflex.vars.base import Var
+
from .base import BaseHTML
class Body(BaseHTML):
@@ -16,98 +17,52 @@ class Body(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Body":
"""Create the component.
@@ -148,98 +103,52 @@ class Address(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Address":
"""Create the component.
@@ -280,98 +189,52 @@ class Article(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Article":
"""Create the component.
@@ -412,98 +275,52 @@ class Aside(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Aside":
"""Create the component.
@@ -544,98 +361,52 @@ class Footer(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Footer":
"""Create the component.
@@ -676,98 +447,52 @@ class Header(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Header":
"""Create the component.
@@ -808,98 +533,52 @@ class H1(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "H1":
"""Create the component.
@@ -940,98 +619,52 @@ class H2(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "H2":
"""Create the component.
@@ -1072,98 +705,52 @@ class H3(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "H3":
"""Create the component.
@@ -1204,98 +791,52 @@ class H4(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "H4":
"""Create the component.
@@ -1336,98 +877,52 @@ class H5(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "H5":
"""Create the component.
@@ -1468,98 +963,52 @@ class H6(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "H6":
"""Create the component.
@@ -1600,98 +1049,52 @@ class Main(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Main":
"""Create the component.
@@ -1732,98 +1135,52 @@ class Nav(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Nav":
"""Create the component.
@@ -1864,98 +1221,52 @@ class Section(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Section":
"""Create the component.
@@ -1989,3 +1300,19 @@ class Section(BaseHTML):
The component.
"""
...
+
+address = Address.create
+article = Article.create
+aside = Aside.create
+body = Body.create
+header = Header.create
+footer = Footer.create
+h1 = H1.create
+h2 = H2.create
+h3 = H3.create
+h4 = H4.create
+h5 = H5.create
+h6 = H6.create
+main = Main.create
+nav = Nav.create
+section = Section.create
diff --git a/reflex/components/el/elements/tables.py b/reflex/components/el/elements/tables.py
index 1277e1bea..8f6cfcba4 100644
--- a/reflex/components/el/elements/tables.py
+++ b/reflex/components/el/elements/tables.py
@@ -1,7 +1,8 @@
"""Element classes. This is an auto-generated file. Do not edit. See ../generate.py."""
+
from typing import Union
-from reflex.vars import Var as Var
+from reflex.vars.base import Var
from .base import BaseHTML
@@ -124,3 +125,15 @@ class Tr(BaseHTML):
# Alignment of the content within the table row
align: Var[Union[str, int, bool]]
+
+
+caption = Caption.create
+col = Col.create
+colgroup = Colgroup.create
+table = Table.create
+tbody = Tbody.create
+td = Td.create
+tfoot = Tfoot.create
+th = Th.create
+thead = Thead.create
+tr = Tr.create
diff --git a/reflex/components/el/elements/tables.pyi b/reflex/components/el/elements/tables.pyi
index 6a81d3fad..4d874f460 100644
--- a/reflex/components/el/elements/tables.pyi
+++ b/reflex/components/el/elements/tables.pyi
@@ -1,14 +1,14 @@
"""Stub file for reflex/components/el/elements/tables.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+from reflex.event import EventType
from reflex.style import Style
-from typing import Union
-from reflex.vars import Var as Var
+from reflex.vars.base import Var
+
from .base import BaseHTML
class Caption(BaseHTML):
@@ -17,101 +17,53 @@ class Caption(BaseHTML):
def create( # type: ignore
cls,
*children,
- align: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ align: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Caption":
"""Create the component.
@@ -153,102 +105,54 @@ class Col(BaseHTML):
def create( # type: ignore
cls,
*children,
- align: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- span: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ align: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ span: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Col":
"""Create the component.
@@ -291,102 +195,54 @@ class Colgroup(BaseHTML):
def create( # type: ignore
cls,
*children,
- align: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- span: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ align: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ span: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Colgroup":
"""Create the component.
@@ -429,104 +285,54 @@ class Table(BaseHTML):
def create( # type: ignore
cls,
*children,
- align: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- summary: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ align: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ summary: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Table":
"""Create the component.
@@ -569,101 +375,53 @@ class Tbody(BaseHTML):
def create( # type: ignore
cls,
*children,
- align: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ align: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Tbody":
"""Create the component.
@@ -705,110 +463,56 @@ class Td(BaseHTML):
def create( # type: ignore
cls,
*children,
- align: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- col_span: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- headers: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- row_span: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ align: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ col_span: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ headers: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ row_span: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Td":
"""Create the component.
@@ -853,101 +557,53 @@ class Tfoot(BaseHTML):
def create( # type: ignore
cls,
*children,
- align: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ align: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Tfoot":
"""Create the component.
@@ -989,113 +645,57 @@ class Th(BaseHTML):
def create( # type: ignore
cls,
*children,
- align: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- col_span: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- headers: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- row_span: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- scope: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ align: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ col_span: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ headers: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ row_span: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ scope: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Th":
"""Create the component.
@@ -1141,101 +741,53 @@ class Thead(BaseHTML):
def create( # type: ignore
cls,
*children,
- align: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ align: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Thead":
"""Create the component.
@@ -1277,101 +829,53 @@ class Tr(BaseHTML):
def create( # type: ignore
cls,
*children,
- align: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ align: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Tr":
"""Create the component.
@@ -1406,3 +910,14 @@ class Tr(BaseHTML):
The component.
"""
...
+
+caption = Caption.create
+col = Col.create
+colgroup = Colgroup.create
+table = Table.create
+tbody = Tbody.create
+td = Td.create
+tfoot = Tfoot.create
+th = Th.create
+thead = Thead.create
+tr = Tr.create
diff --git a/reflex/components/el/elements/typography.py b/reflex/components/el/elements/typography.py
index f8e3769fa..7c55ecce7 100644
--- a/reflex/components/el/elements/typography.py
+++ b/reflex/components/el/elements/typography.py
@@ -1,7 +1,8 @@
"""Element classes. This is an auto-generated file. Do not edit. See ../generate.py."""
+
from typing import Union
-from reflex.vars import Var as Var
+from reflex.vars.base import Var
from .base import BaseHTML
@@ -124,3 +125,19 @@ class Del(BaseHTML):
# Specifies the date and time of when the text was deleted.
date_time: Var[Union[str, int, bool]]
+
+
+blockquote = Blockquote.create
+dd = Dd.create
+div = Div.create
+dl = Dl.create
+dt = Dt.create
+figcaption = Figcaption.create
+hr = Hr.create
+li = Li.create
+ol = Ol.create
+p = P.create
+pre = Pre.create
+ul = Ul.create
+ins = Ins.create
+del_ = Del.create # 'del' is a reserved keyword in Python
diff --git a/reflex/components/el/elements/typography.pyi b/reflex/components/el/elements/typography.pyi
index f6562cacc..548371ce6 100644
--- a/reflex/components/el/elements/typography.pyi
+++ b/reflex/components/el/elements/typography.pyi
@@ -1,14 +1,14 @@
"""Stub file for reflex/components/el/elements/typography.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+from reflex.event import EventType
from reflex.style import Style
-from typing import Union
-from reflex.vars import Var as Var
+from reflex.vars.base import Var
+
from .base import BaseHTML
class Blockquote(BaseHTML):
@@ -17,99 +17,53 @@ class Blockquote(BaseHTML):
def create( # type: ignore
cls,
*children,
- cite: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ cite: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Blockquote":
"""Create the component.
@@ -151,98 +105,52 @@ class Dd(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Dd":
"""Create the component.
@@ -283,98 +191,52 @@ class Div(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Div":
"""Create the component.
@@ -415,98 +277,52 @@ class Dl(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Dl":
"""Create the component.
@@ -547,98 +363,52 @@ class Dt(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Dt":
"""Create the component.
@@ -679,98 +449,52 @@ class Figcaption(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Figcaption":
"""Create the component.
@@ -811,101 +535,53 @@ class Hr(BaseHTML):
def create( # type: ignore
cls,
*children,
- align: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ align: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Hr":
"""Create the component.
@@ -947,98 +623,52 @@ class Li(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Li":
"""Create the component.
@@ -1079,99 +709,53 @@ class Menu(BaseHTML):
def create( # type: ignore
cls,
*children,
- type: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ type: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Menu":
"""Create the component.
@@ -1213,105 +797,55 @@ class Ol(BaseHTML):
def create( # type: ignore
cls,
*children,
- reversed: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- start: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- type: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ reversed: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ start: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ type: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Ol":
"""Create the component.
@@ -1355,98 +889,52 @@ class P(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "P":
"""Create the component.
@@ -1487,98 +975,52 @@ class Pre(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Pre":
"""Create the component.
@@ -1619,98 +1061,52 @@ class Ul(BaseHTML):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Ul":
"""Create the component.
@@ -1751,102 +1147,54 @@ class Ins(BaseHTML):
def create( # type: ignore
cls,
*children,
- cite: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- date_time: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ cite: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ date_time: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Ins":
"""Create the component.
@@ -1889,102 +1237,54 @@ class Del(BaseHTML):
def create( # type: ignore
cls,
*children,
- cite: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- date_time: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ cite: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ date_time: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Del":
"""Create the component.
@@ -2020,3 +1320,18 @@ class Del(BaseHTML):
The component.
"""
...
+
+blockquote = Blockquote.create
+dd = Dd.create
+div = Div.create
+dl = Dl.create
+dt = Dt.create
+figcaption = Figcaption.create
+hr = Hr.create
+li = Li.create
+ol = Ol.create
+p = P.create
+pre = Pre.create
+ul = Ul.create
+ins = Ins.create
+del_ = Del.create
diff --git a/reflex/components/gridjs/datatable.py b/reflex/components/gridjs/datatable.py
index 6c05dfd81..bd568d84a 100644
--- a/reflex/components/gridjs/datatable.py
+++ b/reflex/components/gridjs/datatable.py
@@ -6,17 +6,18 @@ from typing import Any, Dict, List, Union
from reflex.components.component import Component
from reflex.components.tags import Tag
-from reflex.utils import imports, types
+from reflex.utils import types
+from reflex.utils.imports import ImportDict
from reflex.utils.serializers import serialize
-from reflex.vars import BaseVar, ComputedVar, Var
+from reflex.vars.base import LiteralVar, Var, is_computed_var
class Gridjs(Component):
"""A component that wraps a nivo bar component."""
- library = "gridjs-react@6.0.1"
+ library = "gridjs-react@6.1.1"
- lib_dependencies: List[str] = ["gridjs@6.0.6"]
+ lib_dependencies: List[str] = ["gridjs@6.2.0"]
class DataTable(Gridjs):
@@ -64,14 +65,14 @@ class DataTable(Gridjs):
# The annotation should be provided if data is a computed var. We need this to know how to
# render pandas dataframes.
- if isinstance(data, ComputedVar) and data._var_type == Any:
+ if is_computed_var(data) and data._var_type == Any:
raise ValueError(
"Annotation of the computed var assigned to the data field should be provided."
)
if (
columns is not None
- and isinstance(columns, ComputedVar)
+ and is_computed_var(columns)
and columns._var_type == Any
):
raise ValueError(
@@ -102,30 +103,31 @@ class DataTable(Gridjs):
**props,
)
- def _get_imports(self) -> imports.ImportDict:
- return imports.merge_imports(
- super()._get_imports(),
- {"": {imports.ImportVar(tag="gridjs/dist/theme/mermaid.css")}},
- )
+ def add_imports(self) -> ImportDict:
+ """Add the imports for the datatable component.
+
+ Returns:
+ The import dict for the component.
+ """
+ return {"": "gridjs/dist/theme/mermaid.css"}
def _render(self) -> Tag:
if isinstance(self.data, Var) and types.is_dataframe(self.data._var_type):
- self.columns = BaseVar(
- _var_name=f"{self.data._var_name}.columns",
+ self.columns = self.data._replace(
+ _js_expr=f"{self.data._js_expr}.columns",
_var_type=List[Any],
- _var_full_name_needs_state_prefix=True,
- )._replace(merge_var_data=self.data._var_data)
- self.data = BaseVar(
- _var_name=f"{self.data._var_name}.data",
+ )
+ self.data = self.data._replace(
+ _js_expr=f"{self.data._js_expr}.data",
_var_type=List[List[Any]],
- _var_full_name_needs_state_prefix=True,
- )._replace(merge_var_data=self.data._var_data)
+ )
if types.is_dataframe(type(self.data)):
# If given a pandas df break up the data and columns
data = serialize(self.data)
- assert isinstance(data, dict), "Serialized dataframe should be a dict."
- self.columns = Var.create_safe(data["columns"])
- self.data = Var.create_safe(data["data"])
+ if not isinstance(data, dict):
+ raise ValueError("Serialized dataframe should be a dict.")
+ self.columns = LiteralVar.create(data["columns"])
+ self.data = LiteralVar.create(data["data"])
# Render the table.
return super()._render()
diff --git a/reflex/components/gridjs/datatable.pyi b/reflex/components/gridjs/datatable.pyi
index 9a401b63f..ec4a5405a 100644
--- a/reflex/components/gridjs/datatable.pyi
+++ b/reflex/components/gridjs/datatable.pyi
@@ -1,18 +1,15 @@
"""Stub file for reflex/components/gridjs/datatable.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, List, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Any, Dict, List, Union
from reflex.components.component import Component
-from reflex.components.tags import Tag
-from reflex.utils import imports, types
-from reflex.utils.serializers import serialize
-from reflex.vars import BaseVar, ComputedVar, Var
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.utils.imports import ImportDict
+from reflex.vars.base import Var
class Gridjs(Component):
@overload
@@ -26,52 +23,22 @@ class Gridjs(Component):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Gridjs":
"""Create the component.
@@ -97,63 +64,33 @@ class DataTable(Gridjs):
cls,
*children,
data: Optional[Any] = None,
- columns: Optional[Union[Var[List], List]] = None,
+ columns: Optional[Union[List, Var[List]]] = None,
search: Optional[Union[Var[bool], bool]] = None,
sort: Optional[Union[Var[bool], bool]] = None,
resizable: Optional[Union[Var[bool], bool]] = None,
- pagination: Optional[Union[Var[Union[bool, Dict]], Union[bool, Dict]]] = None,
+ pagination: Optional[Union[Dict, Var[Union[Dict, bool]], bool]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DataTable":
"""Create a datatable component.
@@ -180,3 +117,5 @@ class DataTable(Gridjs):
ValueError: If a pandas dataframe is passed in and columns are also provided.
"""
...
+
+ def add_imports(self) -> ImportDict: ...
diff --git a/reflex/components/lucide/icon.py b/reflex/components/lucide/icon.py
index e9cf9ab82..1ee68aaa3 100644
--- a/reflex/components/lucide/icon.py
+++ b/reflex/components/lucide/icon.py
@@ -1,8 +1,8 @@
"""Lucide Icon component."""
from reflex.components.component import Component
-from reflex.utils import console, format
-from reflex.vars import Var
+from reflex.utils import format
+from reflex.vars.base import Var
class LucideIconComponent(Component):
@@ -36,19 +36,6 @@ class Icon(LucideIconComponent):
Returns:
The created component.
"""
-
- def map_deprecated_icon_names_05(tag: str) -> str:
- new_tag = RENAMED_ICONS_05.get(tag)
- if new_tag is not None:
- console.deprecate(
- feature_name=f"icon {tag}",
- reason=f"it was renamed upstream. Use {new_tag} instead.",
- deprecation_version="0.4.6",
- removal_version="0.6.0",
- )
- return new_tag
- return tag
-
if children:
if len(children) == 1 and isinstance(children[0], str):
props["tag"] = children[0]
@@ -62,8 +49,7 @@ class Icon(LucideIconComponent):
if (
not isinstance(props["tag"], str)
- or map_deprecated_icon_names_05(format.to_snake_case(props["tag"]))
- not in LUCIDE_ICON_LIST
+ or format.to_snake_case(props["tag"]) not in LUCIDE_ICON_LIST
):
raise ValueError(
f"Invalid icon tag: {props['tag']}. Please use one of the following: {', '.join(LUCIDE_ICON_LIST[0:25])}, ..."
@@ -76,116 +62,6 @@ class Icon(LucideIconComponent):
return super().create(*children, **props)
-RENAMED_ICONS_05 = {
- "activity_square": "square_activity",
- "alert_circle": "circle_alert",
- "alert_octagon": "octagon_alert",
- "alert_triangle": "triangle_alert",
- "arrow_down_circle": "circle_arrow_down",
- "arrow_down_left_from_circle": "circle_arrow_out_down_left",
- "arrow_down_left_from_square": "square_arrow_out_down_left",
- "arrow_down_left_square": "square_arrow_down_left",
- "arrow_down_right_from_circle": "circle_arrow_out_down_right",
- "arrow_down_right_from_square": "square_arrow_out_down_right",
- "arrow_down_right_square": "square_arrow_down_right",
- "arrow_down_square": "square_arrow_down",
- "arrow_left_circle": "circle_arrow_left",
- "arrow_left_square": "square_arrow_left",
- "arrow_right_circle": "circle_arrow_right",
- "arrow_right_square": "square_arrow_right",
- "arrow_up_circle": "circle_arrow_up",
- "arrow_up_left_from_circle": "circle_arrow_out_up_left",
- "arrow_up_left_from_square": "square_arrow_out_up_left",
- "arrow_up_left_square": "square_arrow_up_left",
- "arrow_up_right_from_circle": "circle_arrow_out_up_right",
- "arrow_up_right_from_square": "square_arrow_out_up_right",
- "arrow_up_right_square": "square_arrow_up_right",
- "arrow_up_square": "square_arrow_up",
- "asterisk_square": "square_asterisk",
- "check_circle": "circle_check_big",
- "check_circle_2": "circle_check",
- "check_square": "square_check_big",
- "check_square_2": "square_check",
- "chevron_down_circle": "circle_chevron_down",
- "chevron_down_square": "square_chevron_down",
- "chevron_left_circle": "circle_chevron_left",
- "chevron_left_square": "square_chevron_left",
- "chevron_right_circle": "circle_chevron_right",
- "chevron_right_square": "square_chevron_right",
- "chevron_up_circle": "circle_chevron_up",
- "chevron_up_square": "square_chevron_up",
- "code_2": "code_xml",
- "code_square": "square_code",
- "contact_2": "contact_round",
- "divide_circle": "circle_divide",
- "divide_square": "square_divide",
- "dot_square": "square_dot",
- "download_cloud": "cloud_download",
- "equal_square": "square_equal",
- "form_input": "rectangle_ellipsis",
- "function_square": "square_function",
- "gantt_chart_square": "square_gantt_chart",
- "gauge_circle": "circle_gauge",
- "globe_2": "earth",
- "help_circle": "circle_help",
- "helping_hand": "hand_helping",
- "ice_cream": "ice_cream_cone",
- "ice_cream_2": "ice_cream_bowl",
- "indent": "indent_increase",
- "kanban_square": "square_kanban",
- "kanban_square_dashed": "square_dashed_kanban",
- "laptop_2": "laptop_minimal",
- "library_square": "square_library",
- "loader_2": "loader_circle",
- "m_square": "square_m",
- "menu_square": "square_menu",
- "mic_2": "mic_vocal",
- "minus_circle": "circle_minus",
- "minus_square": "square_minus",
- "more_horizontal": "ellipsis",
- "more_vertical": "ellipsis_vertical",
- "mouse_pointer_square": "square_mouse_pointer",
- "mouse_pointer_square_dashed": "square_dashed_mouse_pointer",
- "outdent": "indent_decrease",
- "palm_tree": "tree_palm",
- "parking_circle": "circle_parking",
- "parking_circle_off": "circle_parking_off",
- "parking_square": "square_parking",
- "parking_square_off": "square_parking_off",
- "pause_circle": "circle_pause",
- "pause_octagon": "octagon_pause",
- "percent_circle": "circle_percent",
- "percent_diamond": "diamond_percent",
- "percent_square": "square_percent",
- "pi_square": "square_pi",
- "pilcrow_square": "square_pilcrow",
- "play_circle": "circle_play",
- "play_square": "square_play",
- "plus_circle": "circle_plus",
- "plus_square": "square_plus",
- "power_circle": "circle_power",
- "power_square": "square_power",
- "school_2": "university",
- "scissors_square": "square_scissors",
- "scissors_square_dashed_bottom": "square_bottom_dashed_scissors",
- "sigma_square": "square_sigma",
- "slash_circle": "circle_slash",
- "sliders": "sliders_vertical",
- "split_square_horizontal": "square_split_horizontal",
- "split_square_vertical": "square_split_vertical",
- "stop_circle": "circle_stop",
- "subtitles": "captions",
- "test_tube_2": "test_tube_diagonal",
- "unlock": "lock_open",
- "unlock_keyhole": "lock_keyhole_open",
- "upload_cloud": "cloud_upload",
- "wallet_2": "wallet_minimal",
- "wand_2": "wand_sparkles",
- "x_circle": "circle_x",
- "x_octagon": "octagon_x",
- "x_square": "square_x",
-}
-
LUCIDE_ICON_LIST = [
"a_arrow_down",
"a_arrow_up",
diff --git a/reflex/components/lucide/icon.pyi b/reflex/components/lucide/icon.pyi
index f370185fa..661d91dbe 100644
--- a/reflex/components/lucide/icon.pyi
+++ b/reflex/components/lucide/icon.pyi
@@ -1,15 +1,14 @@
"""Stub file for reflex/components/lucide/icon.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
from reflex.components.component import Component
-from reflex.utils import console, format
-from reflex.vars import Var
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
class LucideIconComponent(Component):
@overload
@@ -23,52 +22,22 @@ class LucideIconComponent(Component):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "LucideIconComponent":
"""Create the component.
@@ -100,52 +69,22 @@ class Icon(LucideIconComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Icon":
"""Initialize the Icon component.
@@ -171,115 +110,6 @@ class Icon(LucideIconComponent):
"""
...
-RENAMED_ICONS_05 = {
- "activity_square": "square_activity",
- "alert_circle": "circle_alert",
- "alert_octagon": "octagon_alert",
- "alert_triangle": "triangle_alert",
- "arrow_down_circle": "circle_arrow_down",
- "arrow_down_left_from_circle": "circle_arrow_out_down_left",
- "arrow_down_left_from_square": "square_arrow_out_down_left",
- "arrow_down_left_square": "square_arrow_down_left",
- "arrow_down_right_from_circle": "circle_arrow_out_down_right",
- "arrow_down_right_from_square": "square_arrow_out_down_right",
- "arrow_down_right_square": "square_arrow_down_right",
- "arrow_down_square": "square_arrow_down",
- "arrow_left_circle": "circle_arrow_left",
- "arrow_left_square": "square_arrow_left",
- "arrow_right_circle": "circle_arrow_right",
- "arrow_right_square": "square_arrow_right",
- "arrow_up_circle": "circle_arrow_up",
- "arrow_up_left_from_circle": "circle_arrow_out_up_left",
- "arrow_up_left_from_square": "square_arrow_out_up_left",
- "arrow_up_left_square": "square_arrow_up_left",
- "arrow_up_right_from_circle": "circle_arrow_out_up_right",
- "arrow_up_right_from_square": "square_arrow_out_up_right",
- "arrow_up_right_square": "square_arrow_up_right",
- "arrow_up_square": "square_arrow_up",
- "asterisk_square": "square_asterisk",
- "check_circle": "circle_check_big",
- "check_circle_2": "circle_check",
- "check_square": "square_check_big",
- "check_square_2": "square_check",
- "chevron_down_circle": "circle_chevron_down",
- "chevron_down_square": "square_chevron_down",
- "chevron_left_circle": "circle_chevron_left",
- "chevron_left_square": "square_chevron_left",
- "chevron_right_circle": "circle_chevron_right",
- "chevron_right_square": "square_chevron_right",
- "chevron_up_circle": "circle_chevron_up",
- "chevron_up_square": "square_chevron_up",
- "code_2": "code_xml",
- "code_square": "square_code",
- "contact_2": "contact_round",
- "divide_circle": "circle_divide",
- "divide_square": "square_divide",
- "dot_square": "square_dot",
- "download_cloud": "cloud_download",
- "equal_square": "square_equal",
- "form_input": "rectangle_ellipsis",
- "function_square": "square_function",
- "gantt_chart_square": "square_gantt_chart",
- "gauge_circle": "circle_gauge",
- "globe_2": "earth",
- "help_circle": "circle_help",
- "helping_hand": "hand_helping",
- "ice_cream": "ice_cream_cone",
- "ice_cream_2": "ice_cream_bowl",
- "indent": "indent_increase",
- "kanban_square": "square_kanban",
- "kanban_square_dashed": "square_dashed_kanban",
- "laptop_2": "laptop_minimal",
- "library_square": "square_library",
- "loader_2": "loader_circle",
- "m_square": "square_m",
- "menu_square": "square_menu",
- "mic_2": "mic_vocal",
- "minus_circle": "circle_minus",
- "minus_square": "square_minus",
- "more_horizontal": "ellipsis",
- "more_vertical": "ellipsis_vertical",
- "mouse_pointer_square": "square_mouse_pointer",
- "mouse_pointer_square_dashed": "square_dashed_mouse_pointer",
- "outdent": "indent_decrease",
- "palm_tree": "tree_palm",
- "parking_circle": "circle_parking",
- "parking_circle_off": "circle_parking_off",
- "parking_square": "square_parking",
- "parking_square_off": "square_parking_off",
- "pause_circle": "circle_pause",
- "pause_octagon": "octagon_pause",
- "percent_circle": "circle_percent",
- "percent_diamond": "diamond_percent",
- "percent_square": "square_percent",
- "pi_square": "square_pi",
- "pilcrow_square": "square_pilcrow",
- "play_circle": "circle_play",
- "play_square": "square_play",
- "plus_circle": "circle_plus",
- "plus_square": "square_plus",
- "power_circle": "circle_power",
- "power_square": "square_power",
- "school_2": "university",
- "scissors_square": "square_scissors",
- "scissors_square_dashed_bottom": "square_bottom_dashed_scissors",
- "sigma_square": "square_sigma",
- "slash_circle": "circle_slash",
- "sliders": "sliders_vertical",
- "split_square_horizontal": "square_split_horizontal",
- "split_square_vertical": "square_split_vertical",
- "stop_circle": "circle_stop",
- "subtitles": "captions",
- "test_tube_2": "test_tube_diagonal",
- "unlock": "lock_open",
- "unlock_keyhole": "lock_keyhole_open",
- "upload_cloud": "cloud_upload",
- "wallet_2": "wallet_minimal",
- "wand_2": "wand_sparkles",
- "x_circle": "circle_x",
- "x_octagon": "octagon_x",
- "x_square": "square_x",
-}
LUCIDE_ICON_LIST = [
"a_arrow_down",
"a_arrow_up",
diff --git a/reflex/components/markdown/markdown.py b/reflex/components/markdown/markdown.py
index 9ea4a11a7..b790bf7a1 100644
--- a/reflex/components/markdown/markdown.py
+++ b/reflex/components/markdown/markdown.py
@@ -7,7 +7,6 @@ from functools import lru_cache
from hashlib import md5
from typing import Any, Callable, Dict, Union
-from reflex.compiler import utils
from reflex.components.component import Component, CustomComponent
from reflex.components.radix.themes.layout.list import (
ListItem,
@@ -18,25 +17,28 @@ from reflex.components.radix.themes.typography.heading import Heading
from reflex.components.radix.themes.typography.link import Link
from reflex.components.radix.themes.typography.text import Text
from reflex.components.tags.tag import Tag
-from reflex.utils import imports, types
-from reflex.utils.imports import ImportVar
-from reflex.vars import Var
+from reflex.utils import types
+from reflex.utils.imports import ImportDict, ImportVar
+from reflex.vars.base import LiteralVar, Var
+from reflex.vars.function import ARRAY_ISARRAY
+from reflex.vars.number import ternary_operation
# Special vars used in the component map.
-_CHILDREN = Var.create_safe("children", _var_is_local=False)
-_PROPS = Var.create_safe("...props", _var_is_local=False)
-_MOCK_ARG = Var.create_safe("")
+_CHILDREN = Var(_js_expr="children", _var_type=str)
+_PROPS = Var(_js_expr="...props")
+_PROPS_IN_TAG = Var(_js_expr="{...props}")
+_MOCK_ARG = Var(_js_expr="", _var_type=str)
# Special remark plugins.
-_REMARK_MATH = Var.create_safe("remarkMath", _var_is_local=False)
-_REMARK_GFM = Var.create_safe("remarkGfm", _var_is_local=False)
-_REMARK_UNWRAP_IMAGES = Var.create_safe("remarkUnwrapImages", _var_is_local=False)
-_REMARK_PLUGINS = Var.create_safe([_REMARK_MATH, _REMARK_GFM, _REMARK_UNWRAP_IMAGES])
+_REMARK_MATH = Var(_js_expr="remarkMath")
+_REMARK_GFM = Var(_js_expr="remarkGfm")
+_REMARK_UNWRAP_IMAGES = Var(_js_expr="remarkUnwrapImages")
+_REMARK_PLUGINS = LiteralVar.create([_REMARK_MATH, _REMARK_GFM, _REMARK_UNWRAP_IMAGES])
# Special rehype plugins.
-_REHYPE_KATEX = Var.create_safe("rehypeKatex", _var_is_local=False)
-_REHYPE_RAW = Var.create_safe("rehypeRaw", _var_is_local=False)
-_REHYPE_PLUGINS = Var.create_safe([_REHYPE_KATEX, _REHYPE_RAW])
+_REHYPE_KATEX = Var(_js_expr="rehypeKatex")
+_REHYPE_RAW = Var(_js_expr="rehypeRaw")
+_REHYPE_PLUGINS = LiteralVar.create([_REHYPE_KATEX, _REHYPE_RAW])
# These tags do NOT get props passed to them
NO_PROPS_TAGS = ("ul", "ol", "li")
@@ -67,7 +69,7 @@ def get_base_component_map() -> dict[str, Callable]:
"a": lambda value: Link.create(value),
"code": lambda value: Code.create(value),
"codeblock": lambda value, **props: CodeBlock.create(
- value, margin_y="1em", **props
+ value, margin_y="1em", wrap_long_lines=True, **props
),
}
@@ -95,12 +97,16 @@ class Markdown(Component):
*children: The children of the component.
**props: The properties of the component.
+ Raises:
+ ValueError: If the children are not valid.
+
Returns:
The markdown component.
"""
- assert (
- len(children) == 1 and types._isinstance(children[0], Union[str, Var])
- ), "Markdown component must have exactly one child containing the markdown source."
+ if len(children) != 1 or not types._isinstance(children[0], Union[str, Var]):
+ raise ValueError(
+ "Markdown component must have exactly one child containing the markdown source."
+ )
# Update the base component map with the custom component map.
component_map = {**get_base_component_map(), **props.pop("component_map", {})}
@@ -141,47 +147,41 @@ class Markdown(Component):
return custom_components
- def _get_imports(self) -> imports.ImportDict:
- # Import here to avoid circular imports.
- from reflex.components.datadisplay.code import CodeBlock
+ def add_imports(self) -> ImportDict | list[ImportDict]:
+ """Add imports for the markdown component.
+
+ Returns:
+ The imports for the markdown component.
+ """
+ from reflex.components.datadisplay.code import CodeBlock, Theme
from reflex.components.radix.themes.typography.code import Code
- imports = super()._get_imports()
-
- # Special markdown imports.
- imports.update(
+ return [
{
- "": [ImportVar(tag="katex/dist/katex.min.css")],
- "remark-math@5.1.1": [
- ImportVar(tag=_REMARK_MATH._var_name, is_default=True)
- ],
- "remark-gfm@3.0.1": [
- ImportVar(tag=_REMARK_GFM._var_name, is_default=True)
- ],
- "remark-unwrap-images@4.0.0": [
- ImportVar(tag=_REMARK_UNWRAP_IMAGES._var_name, is_default=True)
- ],
- "rehype-katex@6.0.3": [
- ImportVar(tag=_REHYPE_KATEX._var_name, is_default=True)
- ],
- "rehype-raw@6.1.1": [
- ImportVar(tag=_REHYPE_RAW._var_name, is_default=True)
- ],
- }
- )
-
- # Get the imports for each component.
- for component in self.component_map.values():
- imports = utils.merge_imports(
- imports, component(_MOCK_ARG)._get_all_imports()
- )
-
- # Get the imports for the code components.
- imports = utils.merge_imports(
- imports, CodeBlock.create(theme="light")._get_imports()
- )
- imports = utils.merge_imports(imports, Code.create()._get_imports())
- return imports
+ "": "katex/dist/katex.min.css",
+ "remark-math@5.1.1": ImportVar(
+ tag=_REMARK_MATH._js_expr, is_default=True
+ ),
+ "remark-gfm@3.0.1": ImportVar(
+ tag=_REMARK_GFM._js_expr, is_default=True
+ ),
+ "remark-unwrap-images@4.0.0": ImportVar(
+ tag=_REMARK_UNWRAP_IMAGES._js_expr, is_default=True
+ ),
+ "rehype-katex@6.0.3": ImportVar(
+ tag=_REHYPE_KATEX._js_expr, is_default=True
+ ),
+ "rehype-raw@6.1.1": ImportVar(
+ tag=_REHYPE_RAW._js_expr, is_default=True
+ ),
+ },
+ *[
+ component(_MOCK_ARG)._get_all_imports() # type: ignore
+ for component in self.component_map.values()
+ ],
+ CodeBlock.create(theme=Theme.light)._get_imports(),
+ Code.create()._get_imports(),
+ ]
def get_component(self, tag: str, **props) -> Component:
"""Get the component for a tag and props.
@@ -200,19 +200,27 @@ class Markdown(Component):
if tag not in self.component_map:
raise ValueError(f"No markdown component found for tag: {tag}.")
- special_props = {_PROPS}
- children = [_CHILDREN]
+ special_props = [_PROPS_IN_TAG]
+ children = [
+ _CHILDREN
+ if tag != "codeblock"
+ # For codeblock, the mapping for some cases returns an array of elements. Let's join them into a string.
+ else ternary_operation(
+ ARRAY_ISARRAY.call(_CHILDREN), # type: ignore
+ _CHILDREN.to(list).join("\n"),
+ _CHILDREN,
+ ).to(str)
+ ]
# For certain tags, the props from the markdown renderer are not actually valid for the component.
if tag in NO_PROPS_TAGS:
- special_props = set()
+ special_props = []
# If the children are set as a prop, don't pass them as children.
children_prop = props.pop("children", None)
if children_prop is not None:
- special_props.add(Var.create_safe(f"children={str(children_prop)}"))
+ special_props.append(Var(_js_expr=f"children={{{str(children_prop)}}}"))
children = []
-
# Get the component.
component = self.component_map[tag](*children, **props).set(
special_props=special_props
@@ -229,21 +237,24 @@ class Markdown(Component):
Returns:
The formatted component.
"""
- return str(self.get_component(tag, **props)).replace("\n", " ")
+ return str(self.get_component(tag, **props)).replace("\n", "")
- def format_component_map(self) -> dict[str, str]:
+ def format_component_map(self) -> dict[str, Var]:
"""Format the component map for rendering.
Returns:
The formatted component map.
"""
components = {
- tag: f"{{({{node, {_CHILDREN._var_name}, {_PROPS._var_name}}}) => {self.format_component(tag)}}}"
+ tag: Var(
+ _js_expr=f"(({{node, {_CHILDREN._js_expr}, {_PROPS._js_expr}}}) => ({self.format_component(tag)}))"
+ )
for tag in self.component_map
}
# Separate out inline code and code blocks.
- components["code"] = f"""{{({{node, inline, className, {_CHILDREN._var_name}, {_PROPS._var_name}}}) => {{
+ components["code"] = Var(
+ _js_expr=f"""(({{node, inline, className, {_CHILDREN._js_expr}, {_PROPS._js_expr}}}) => {{
const match = (className || '').match(/language-(?.*)/);
const language = match ? match[1] : '';
if (language) {{
@@ -259,9 +270,10 @@ class Markdown(Component):
return inline ? (
{self.format_component("code")}
) : (
- {self.format_component("codeblock", language=Var.create_safe("language", _var_is_local=False))}
+ {self.format_component("codeblock", language=Var(_js_expr="language", _var_type=str))}
);
- }}}}""".replace("\n", " ")
+ }})""".replace("\n", " ")
+ )
return components
@@ -286,7 +298,7 @@ class Markdown(Component):
function {self._get_component_map_name()} () {{
{formatted_hooks}
return (
- {str(Var.create(self.format_component_map()))}
+ {str(LiteralVar.create(self.format_component_map()))}
)
}}
"""
@@ -298,14 +310,8 @@ class Markdown(Component):
.add_props(
remark_plugins=_REMARK_PLUGINS,
rehype_plugins=_REHYPE_PLUGINS,
+ components=Var(_js_expr=f"{self._get_component_map_name()}()"),
)
.remove_props("componentMap", "componentMapHash")
)
- tag.special_props.add(
- Var.create_safe(
- f"components={{{self._get_component_map_name()}()}}",
- _var_is_local=True,
- _var_is_string=False,
- ),
- )
return tag
diff --git a/reflex/components/markdown/markdown.pyi b/reflex/components/markdown/markdown.pyi
index 9ca8b11b0..1cad04013 100644
--- a/reflex/components/markdown/markdown.pyi
+++ b/reflex/components/markdown/markdown.pyi
@@ -1,41 +1,28 @@
"""Stub file for reflex/components/markdown/markdown.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-import textwrap
from functools import lru_cache
-from hashlib import md5
-from typing import Any, Callable, Dict, Union
-from reflex.compiler import utils
-from reflex.components.component import Component, CustomComponent
-from reflex.components.radix.themes.layout.list import (
- ListItem,
- OrderedList,
- UnorderedList,
-)
-from reflex.components.radix.themes.typography.heading import Heading
-from reflex.components.radix.themes.typography.link import Link
-from reflex.components.radix.themes.typography.text import Text
-from reflex.components.tags.tag import Tag
-from reflex.utils import imports, types
-from reflex.utils.imports import ImportVar
-from reflex.vars import Var
+from typing import Any, Callable, Dict, Optional, Union, overload
-_CHILDREN = Var.create_safe("children", _var_is_local=False)
-_PROPS = Var.create_safe("...props", _var_is_local=False)
-_MOCK_ARG = Var.create_safe("")
-_REMARK_MATH = Var.create_safe("remarkMath", _var_is_local=False)
-_REMARK_GFM = Var.create_safe("remarkGfm", _var_is_local=False)
-_REMARK_UNWRAP_IMAGES = Var.create_safe("remarkUnwrapImages", _var_is_local=False)
-_REMARK_PLUGINS = Var.create_safe([_REMARK_MATH, _REMARK_GFM, _REMARK_UNWRAP_IMAGES])
-_REHYPE_KATEX = Var.create_safe("rehypeKatex", _var_is_local=False)
-_REHYPE_RAW = Var.create_safe("rehypeRaw", _var_is_local=False)
-_REHYPE_PLUGINS = Var.create_safe([_REHYPE_KATEX, _REHYPE_RAW])
+from reflex.components.component import Component
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.utils.imports import ImportDict
+from reflex.vars.base import LiteralVar, Var
+
+_CHILDREN = Var(_js_expr="children", _var_type=str)
+_PROPS = Var(_js_expr="...props")
+_PROPS_IN_TAG = Var(_js_expr="{...props}")
+_MOCK_ARG = Var(_js_expr="", _var_type=str)
+_REMARK_MATH = Var(_js_expr="remarkMath")
+_REMARK_GFM = Var(_js_expr="remarkGfm")
+_REMARK_UNWRAP_IMAGES = Var(_js_expr="remarkUnwrapImages")
+_REMARK_PLUGINS = LiteralVar.create([_REMARK_MATH, _REMARK_GFM, _REMARK_UNWRAP_IMAGES])
+_REHYPE_KATEX = Var(_js_expr="rehypeKatex")
+_REHYPE_RAW = Var(_js_expr="rehypeRaw")
+_REHYPE_PLUGINS = LiteralVar.create([_REHYPE_KATEX, _REHYPE_RAW])
NO_PROPS_TAGS = ("ul", "ol", "li")
@lru_cache
@@ -55,52 +42,22 @@ class Markdown(Component):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Markdown":
"""Create a markdown component.
@@ -116,10 +73,15 @@ class Markdown(Component):
custom_attrs: custom attribute
**props: The properties of the component.
+ Raises:
+ ValueError: If the children are not valid.
+
Returns:
The markdown component.
"""
...
+
+ def add_imports(self) -> ImportDict | list[ImportDict]: ...
def get_component(self, tag: str, **props) -> Component: ...
def format_component(self, tag: str, **props) -> str: ...
- def format_component_map(self) -> dict[str, str]: ...
+ def format_component_map(self) -> dict[str, Var]: ...
diff --git a/reflex/components/media/__init__.py b/reflex/components/media/__init__.py
deleted file mode 100644
index ee11c77e0..000000000
--- a/reflex/components/media/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-"""Temporary shim for Chakra icon class."""
diff --git a/reflex/components/media/icon.py b/reflex/components/media/icon.py
deleted file mode 100644
index c60905083..000000000
--- a/reflex/components/media/icon.py
+++ /dev/null
@@ -1,2 +0,0 @@
-"""Shim for reflex.components.chakra.media.icon."""
-from reflex.components.chakra.media.icon import *
diff --git a/reflex/components/moment/__init__.py b/reflex/components/moment/__init__.py
index f144680fe..9f4987c56 100644
--- a/reflex/components/moment/__init__.py
+++ b/reflex/components/moment/__init__.py
@@ -1,5 +1,5 @@
"""Moment.js component."""
-from .moment import Moment
+from .moment import Moment, MomentDelta
moment = Moment.create
diff --git a/reflex/components/moment/moment.py b/reflex/components/moment/moment.py
index 53e199c4e..4ac835b35 100644
--- a/reflex/components/moment/moment.py
+++ b/reflex/components/moment/moment.py
@@ -1,25 +1,27 @@
"""Moment component for humanized date rendering."""
-from typing import Any, Dict, List, Optional
+import dataclasses
+from typing import List, Optional
-from reflex.base import Base
-from reflex.components.component import Component, NoSSRComponent
-from reflex.utils import imports
-from reflex.vars import Var
+from reflex.components.component import NoSSRComponent
+from reflex.event import EventHandler, identity_event
+from reflex.utils.imports import ImportDict
+from reflex.vars.base import LiteralVar, Var
-class MomentDelta(Base):
+@dataclasses.dataclass(frozen=True)
+class MomentDelta:
"""A delta used for add/subtract prop in Moment."""
- years: Optional[int]
- quarters: Optional[int]
- months: Optional[int]
- weeks: Optional[int]
- days: Optional[int]
- hours: Optional[int]
- minutess: Optional[int]
- seconds: Optional[int]
- milliseconds: Optional[int]
+ years: Optional[int] = dataclasses.field(default=None)
+ quarters: Optional[int] = dataclasses.field(default=None)
+ months: Optional[int] = dataclasses.field(default=None)
+ weeks: Optional[int] = dataclasses.field(default=None)
+ days: Optional[int] = dataclasses.field(default=None)
+ hours: Optional[int] = dataclasses.field(default=None)
+ minutess: Optional[int] = dataclasses.field(default=None)
+ seconds: Optional[int] = dataclasses.field(default=None)
+ milliseconds: Optional[int] = dataclasses.field(default=None)
class Moment(NoSSRComponent):
@@ -90,38 +92,27 @@ class Moment(NoSSRComponent):
# Display the date in the given timezone.
tz: Var[str]
- def _get_imports(self) -> imports.ImportDict:
- merged_imports = super()._get_imports()
+ # The locale to use when rendering.
+ locale: Var[str]
+
+ # Fires when the date changes.
+ on_change: EventHandler[identity_event(str)]
+
+ def add_imports(self) -> ImportDict:
+ """Add the imports for the Moment component.
+
+ Returns:
+ The import dict for the component.
+ """
+ imports = {}
+
+ if isinstance(self.locale, LiteralVar):
+ imports[""] = f"moment/locale/{self.locale._var_value}"
+ elif self.locale is not None:
+ # If the user is using a variable for the locale, we can't know the
+ # value at compile time so import all locales available.
+ imports[""] = "moment/min/locales"
if self.tz is not None:
- merged_imports = imports.merge_imports(
- merged_imports,
- {"moment-timezone": {imports.ImportVar(tag="")}},
- )
- return merged_imports
+ imports["moment-timezone"] = ""
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
-
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- "on_change": lambda date: [date],
- }
-
- @classmethod
- def create(cls, *children, **props) -> Component:
- """Create a Moment component.
-
- Args:
- *children: The children of the component.
- **props: The properties of the component.
-
- Returns:
- The Moment Component.
- """
- comp = super().create(*children, **props)
- if "tz" in props:
- comp.lib_dependencies.append("moment-timezone")
- return comp
+ return imports
diff --git a/reflex/components/moment/moment.pyi b/reflex/components/moment/moment.pyi
index 73ad8ca5d..16221ff63 100644
--- a/reflex/components/moment/moment.pyi
+++ b/reflex/components/moment/moment.pyi
@@ -1,19 +1,19 @@
"""Stub file for reflex/components/moment/moment.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+import dataclasses
+from typing import Any, Dict, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+from reflex.components.component import NoSSRComponent
+from reflex.event import EventType
from reflex.style import Style
-from typing import Any, Dict, List, Optional
-from reflex.base import Base
-from reflex.components.component import Component, NoSSRComponent
-from reflex.utils import imports
-from reflex.vars import Var
+from reflex.utils.imports import ImportDict
+from reflex.vars.base import Var
-class MomentDelta(Base):
+@dataclasses.dataclass(frozen=True)
+class MomentDelta:
years: Optional[int]
quarters: Optional[int]
months: Optional[int]
@@ -25,7 +25,7 @@ class MomentDelta(Base):
milliseconds: Optional[int]
class Moment(NoSSRComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
+ def add_imports(self) -> ImportDict: ...
@overload
@classmethod
def create( # type: ignore
@@ -35,8 +35,8 @@ class Moment(NoSSRComponent):
format: Optional[Union[Var[str], str]] = None,
trim: Optional[Union[Var[bool], bool]] = None,
parse: Optional[Union[Var[str], str]] = None,
- add: Optional[Union[Var[MomentDelta], MomentDelta]] = None,
- subtract: Optional[Union[Var[MomentDelta], MomentDelta]] = None,
+ add: Optional[Union[MomentDelta, Var[MomentDelta]]] = None,
+ subtract: Optional[Union[MomentDelta, Var[MomentDelta]]] = None,
from_now: Optional[Union[Var[bool], bool]] = None,
from_now_during: Optional[Union[Var[int], int]] = None,
to_now: Optional[Union[Var[bool], bool]] = None,
@@ -51,63 +51,32 @@ class Moment(NoSSRComponent):
unix: Optional[Union[Var[bool], bool]] = None,
local: Optional[Union[Var[bool], bool]] = None,
tz: Optional[Union[Var[str], str]] = None,
+ locale: Optional[Union[Var[str], str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_change: Optional[EventType[str]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Moment":
- """Create a Moment component.
+ """Create the component.
Args:
*children: The children of the component.
@@ -131,15 +100,17 @@ class Moment(NoSSRComponent):
unix: Tells Moment to parse the given date value as a unix timestamp.
local: Outputs the result in local time.
tz: Display the date in the given timezone.
+ locale: The locale to use when rendering.
+ on_change: Fires when the date changes.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
class_name: The class name for the component.
autofocus: Whether the component should take the focus once the page is loaded
custom_attrs: custom attribute
- **props: The properties of the component.
+ **props: The props of the component.
Returns:
- The Moment Component.
+ The component.
"""
...
diff --git a/reflex/components/next/base.py b/reflex/components/next/base.py
index f962497d3..1dd3db437 100644
--- a/reflex/components/next/base.py
+++ b/reflex/components/next/base.py
@@ -1,4 +1,5 @@
"""Base for NextJS components."""
+
from reflex.components.component import Component
diff --git a/reflex/components/next/base.pyi b/reflex/components/next/base.pyi
index d18610e16..1d49c5e66 100644
--- a/reflex/components/next/base.pyi
+++ b/reflex/components/next/base.pyi
@@ -1,13 +1,14 @@
"""Stub file for reflex/components/next/base.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
from reflex.components.component import Component
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
class NextComponent(Component):
...
@@ -23,52 +24,22 @@ class NextComponent(Component):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "NextComponent":
"""Create the component.
diff --git a/reflex/components/next/image.py b/reflex/components/next/image.py
index 10556d5ad..fe74b0935 100644
--- a/reflex/components/next/image.py
+++ b/reflex/components/next/image.py
@@ -1,9 +1,10 @@
"""Image component from next/image."""
-from typing import Any, Dict, Literal, Optional, Union
+from typing import Any, Literal, Optional, Union
+from reflex.event import EventHandler, empty_event
from reflex.utils import types
-from reflex.vars import Var
+from reflex.vars.base import Var
from .base import NextComponent
@@ -54,17 +55,11 @@ class Image(NextComponent):
# A Data URL to be used as a placeholder image before the src image successfully loads. Only takes effect when combined with placeholder="blur".
blurDataURL: Var[str]
- def get_event_triggers(self) -> Dict[str, Any]:
- """The event triggers of the component.
+ # Fires when the image has loaded.
+ on_load: EventHandler[empty_event]
- Returns:
- The dict describing the event triggers.
- """
- return {
- **super().get_event_triggers(),
- "on_load": lambda: [],
- "on_error": lambda: [],
- }
+ # Fires when the image has an error.
+ on_error: EventHandler[empty_event]
@classmethod
def create(
@@ -107,8 +102,4 @@ class Image(NextComponent):
# mysteriously, following `sizes` prop is needed to avoid blury images.
props["sizes"] = "100vw"
- src = props.get("src", None)
- if src is not None and not isinstance(src, (Var)):
- props["src"] = Var.create(value=src, _var_is_string=True)
-
return super().create(*children, **props)
diff --git a/reflex/components/next/image.pyi b/reflex/components/next/image.pyi
index c1ee16374..405f8ac52 100644
--- a/reflex/components/next/image.pyi
+++ b/reflex/components/next/image.pyi
@@ -1,36 +1,34 @@
"""Stub file for reflex/components/next/image.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+
+from reflex.event import EventType
from reflex.style import Style
-from typing import Any, Dict, Literal, Optional, Union
-from reflex.utils import types
-from reflex.vars import Var
+from reflex.vars.base import Var
+
from .base import NextComponent
class Image(NextComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- width: Optional[Union[str, int]] = None,
- height: Optional[Union[str, int]] = None,
- src: Optional[Union[Var[Any], Any]] = None,
+ width: Optional[Union[int, str]] = None,
+ height: Optional[Union[int, str]] = None,
+ src: Optional[Union[Any, Var[Any]]] = None,
alt: Optional[Union[Var[str], str]] = None,
- loader: Optional[Union[Var[Any], Any]] = None,
+ loader: Optional[Union[Any, Var[Any]]] = None,
fill: Optional[Union[Var[bool], bool]] = None,
sizes: Optional[Union[Var[str], str]] = None,
quality: Optional[Union[Var[int], int]] = None,
priority: Optional[Union[Var[bool], bool]] = None,
placeholder: Optional[Union[Var[str], str]] = None,
loading: Optional[
- Union[Var[Literal["lazy", "eager"]], Literal["lazy", "eager"]]
+ Union[Literal["eager", "lazy"], Var[Literal["eager", "lazy"]]]
] = None,
blurDataURL: Optional[Union[Var[str], str]] = None,
style: Optional[Style] = None,
@@ -39,58 +37,24 @@ class Image(NextComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_error: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_load: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_error: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_load: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Image":
"""Create an Image component from next/image.
@@ -108,6 +72,8 @@ class Image(NextComponent):
placeholder: A placeholder to use while the image is loading. Possible values are blur, empty, or data:image/.... Defaults to empty.
loading: Allows passing CSS styles to the underlying image element. style: Var[Any] The loading behavior of the image. Defaults to lazy. Can hurt performance, recommended to use `priority` instead.
blurDataURL: A Data URL to be used as a placeholder image before the src image successfully loads. Only takes effect when combined with placeholder="blur".
+ on_load: Fires when the image has loaded.
+ on_error: Fires when the image has an error.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
diff --git a/reflex/components/next/link.py b/reflex/components/next/link.py
index be32cd8e5..0f7c81296 100644
--- a/reflex/components/next/link.py
+++ b/reflex/components/next/link.py
@@ -1,7 +1,7 @@
"""A link component."""
from reflex.components.component import Component
-from reflex.vars import Var
+from reflex.vars.base import Var
class NextLink(Component):
diff --git a/reflex/components/next/link.pyi b/reflex/components/next/link.pyi
index e382febdd..fa9ae530f 100644
--- a/reflex/components/next/link.pyi
+++ b/reflex/components/next/link.pyi
@@ -1,14 +1,14 @@
"""Stub file for reflex/components/next/link.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
from reflex.components.component import Component
-from reflex.vars import Var
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
class NextLink(Component):
@overload
@@ -24,52 +24,22 @@ class NextLink(Component):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "NextLink":
"""Create the component.
diff --git a/reflex/components/next/video.py b/reflex/components/next/video.py
index ae6007671..435f4401f 100644
--- a/reflex/components/next/video.py
+++ b/reflex/components/next/video.py
@@ -3,7 +3,7 @@
from typing import Optional
from reflex.components.component import Component
-from reflex.vars import Var
+from reflex.vars.base import Var
from .base import NextComponent
diff --git a/reflex/components/next/video.pyi b/reflex/components/next/video.pyi
index 64abc76d0..f8c93b6f1 100644
--- a/reflex/components/next/video.pyi
+++ b/reflex/components/next/video.pyi
@@ -1,15 +1,15 @@
"""Stub file for reflex/components/next/video.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Optional
from reflex.components.component import Component
-from reflex.vars import Var
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
+
from .base import NextComponent
class Video(NextComponent):
@@ -26,52 +26,22 @@ class Video(NextComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Video":
"""Create a Video component.
diff --git a/reflex/components/plotly/plotly.py b/reflex/components/plotly/plotly.py
index 7a0dd835f..c93488d40 100644
--- a/reflex/components/plotly/plotly.py
+++ b/reflex/components/plotly/plotly.py
@@ -1,45 +1,279 @@
"""Component for displaying a plotly graph."""
+from __future__ import annotations
+
from typing import Any, Dict, List
-from reflex.components.component import NoSSRComponent
-from reflex.vars import Var
+from reflex.base import Base
+from reflex.components.component import Component, NoSSRComponent
+from reflex.components.core.cond import color_mode_cond
+from reflex.event import EventHandler
+from reflex.utils import console
+from reflex.vars.base import LiteralVar, Var
try:
- from plotly.graph_objects import Figure
+ from plotly.graph_objects import Figure, layout
+
+ Template = layout.Template
except ImportError:
+ console.warn("Plotly is not installed. Please run `pip install plotly`.")
Figure = Any # type: ignore
+ Template = Any # type: ignore
-class PlotlyLib(NoSSRComponent):
- """A component that wraps a plotly lib."""
+def _event_data_signature(e0: Var) -> List[Any]:
+ """For plotly events with event data and no points.
+
+ Args:
+ e0: The event data.
+
+ Returns:
+ The event key extracted from the event data (if defined).
+ """
+ return [Var(_js_expr=f"{e0}?.event")]
+
+
+def _event_points_data_signature(e0: Var) -> List[Any]:
+ """For plotly events with event data containing a point array.
+
+ Args:
+ e0: The event data.
+
+ Returns:
+ The event data and the extracted points.
+ """
+ return [
+ Var(_js_expr=f"{e0}?.event"),
+ Var(_js_expr=f"extractPoints({e0}?.points)"),
+ ]
+
+
+class _ButtonClickData(Base):
+ """Event data structure for plotly UI buttons."""
+
+ menu: Any
+ button: Any
+ active: Any
+
+
+def _button_click_signature(e0: _ButtonClickData) -> List[Any]:
+ """For plotly button click events.
+
+ Args:
+ e0: The button click data.
+
+ Returns:
+ The menu, button, and active state.
+ """
+ return [e0.menu, e0.button, e0.active]
+
+
+def _passthrough_signature(e0: Var) -> List[Any]:
+ """For plotly events with arbitrary serializable data, passed through directly.
+
+ Args:
+ e0: The event data.
+
+ Returns:
+ The event data.
+ """
+ return [e0]
+
+
+def _null_signature() -> List[Any]:
+ """For plotly events with no data or non-serializable data. Nothing passed through.
+
+ Returns:
+ An empty list (nothing passed through).
+ """
+ return []
+
+
+class Plotly(NoSSRComponent):
+ """Display a plotly graph."""
library = "react-plotly.js@2.6.0"
- lib_dependencies: List[str] = ["plotly.js@2.22.0"]
-
-
-class Plotly(PlotlyLib):
- """Display a plotly graph."""
+ lib_dependencies: List[str] = ["plotly.js@2.35.2"]
tag = "Plot"
is_default = True
# The figure to display. This can be a plotly figure or a plotly data json.
- data: Var[Figure]
+ data: Var[Figure] # type: ignore
# The layout of the graph.
layout: Var[Dict]
+ # The template for visual appearance of the graph.
+ template: Var[Template] # type: ignore
+
# The config of the graph.
config: Var[Dict]
- # The width of the graph.
- width: Var[str]
-
- # The height of the graph.
- height: Var[str]
-
# If true, the graph will resize when the window is resized.
- use_resize_handler: Var[bool]
+ use_resize_handler: Var[bool] = LiteralVar.create(True)
+
+ # Fired after the plot is redrawn.
+ on_after_plot: EventHandler[_passthrough_signature]
+
+ # Fired after the plot was animated.
+ on_animated: EventHandler[_null_signature]
+
+ # Fired while animating a single frame (does not currently pass data through).
+ on_animating_frame: EventHandler[_null_signature]
+
+ # Fired when an animation is interrupted (to start a new animation for example).
+ on_animation_interrupted: EventHandler[_null_signature]
+
+ # Fired when the plot is responsively sized.
+ on_autosize: EventHandler[_event_data_signature]
+
+ # Fired whenever mouse moves over a plot.
+ on_before_hover: EventHandler[_event_data_signature]
+
+ # Fired when a plotly UI button is clicked.
+ on_button_clicked: EventHandler[_button_click_signature]
+
+ # Fired when the plot is clicked.
+ on_click: EventHandler[_event_points_data_signature]
+
+ # Fired when a selection is cleared (via double click).
+ on_deselect: EventHandler[_null_signature]
+
+ # Fired when the plot is double clicked.
+ on_double_click: EventHandler[_passthrough_signature]
+
+ # Fired when a plot element is hovered over.
+ on_hover: EventHandler[_event_points_data_signature]
+
+ # Fired after the plot is layed out (zoom, pan, etc).
+ on_relayout: EventHandler[_passthrough_signature]
+
+ # Fired while the plot is being layed out.
+ on_relayouting: EventHandler[_passthrough_signature]
+
+ # Fired after the plot style is changed.
+ on_restyle: EventHandler[_passthrough_signature]
+
+ # Fired after the plot is redrawn.
+ on_redraw: EventHandler[_event_data_signature]
+
+ # Fired after selecting plot elements.
+ on_selected: EventHandler[_event_points_data_signature]
+
+ # Fired while dragging a selection.
+ on_selecting: EventHandler[_event_points_data_signature]
+
+ # Fired while an animation is occuring.
+ on_transitioning: EventHandler[_event_data_signature]
+
+ # Fired when a transition is stopped early.
+ on_transition_interrupted: EventHandler[_event_data_signature]
+
+ # Fired when a hovered element is no longer hovered.
+ on_unhover: EventHandler[_event_points_data_signature]
+
+ def add_imports(self) -> dict[str, str]:
+ """Add imports for the plotly component.
+
+ Returns:
+ The imports for the plotly component.
+ """
+ return {
+ # For merging plotly data/layout/templates.
+ "mergician@v2.0.2": "mergician"
+ }
+
+ def add_custom_code(self) -> list[str]:
+ """Add custom codes for processing the plotly points data.
+
+ Returns:
+ Custom code snippets for the module level.
+ """
+ return [
+ "const removeUndefined = (obj) => {Object.keys(obj).forEach(key => obj[key] === undefined && delete obj[key]); return obj}",
+ """
+const extractPoints = (points) => {
+ if (!points) return [];
+ return points.map(point => {
+ const bbox = point.bbox ? removeUndefined({
+ x0: point.bbox.x0,
+ x1: point.bbox.x1,
+ y0: point.bbox.y0,
+ y1: point.bbox.y1,
+ z0: point.bbox.y0,
+ z1: point.bbox.y1,
+ }) : undefined;
+ return removeUndefined({
+ x: point.x,
+ y: point.y,
+ z: point.z,
+ lat: point.lat,
+ lon: point.lon,
+ curveNumber: point.curveNumber,
+ pointNumber: point.pointNumber,
+ pointNumbers: point.pointNumbers,
+ pointIndex: point.pointIndex,
+ 'marker.color': point['marker.color'],
+ 'marker.size': point['marker.size'],
+ bbox: bbox,
+ })
+ })
+}
+""",
+ ]
+
+ @classmethod
+ def create(cls, *children, **props) -> Component:
+ """Create the Plotly component.
+
+ Args:
+ *children: The children of the component.
+ **props: The properties of the component.
+
+ Returns:
+ The Plotly component.
+ """
+ from plotly.io import templates
+
+ responsive_template = color_mode_cond(
+ light=LiteralVar.create(templates["plotly"]),
+ dark=LiteralVar.create(templates["plotly_dark"]),
+ )
+ if isinstance(responsive_template, Var):
+ # Mark the conditional Var as a Template to avoid type mismatch
+ responsive_template = responsive_template.to(Template)
+ props.setdefault("template", responsive_template)
+ return super().create(*children, **props)
+
+ def _exclude_props(self) -> set[str]:
+ # These props are handled specially in the _render function
+ return {"data", "layout", "template"}
+
+ def _render(self):
+ tag = super()._render()
+ figure = self.data.to(dict)
+ merge_dicts = [] # Data will be merged and spread from these dict Vars
+ if self.layout is not None:
+ # Why is this not a literal dict? Great question... it didn't work
+ # reliably because of how _var_name_unwrapped strips the outer curly
+ # brackets if any of the contained Vars depend on state.
+ layout_dict = LiteralVar.create({"layout": self.layout})
+ merge_dicts.append(layout_dict)
+ if self.template is not None:
+ template_dict = LiteralVar.create({"layout": {"template": self.template}})
+ merge_dicts.append(template_dict.without_data())
+ if merge_dicts:
+ tag.special_props.append(
+ # Merge all dictionaries and spread the result over props.
+ Var(
+ _js_expr=f"{{...mergician({str(figure)},"
+ f"{','.join(str(md) for md in merge_dicts)})}}",
+ ),
+ )
+ else:
+ # Spread the figure dict over props, nothing to merge.
+ tag.special_props.append(Var(_js_expr=f"{{...{str(figure)}}}"))
+ return tag
diff --git a/reflex/components/plotly/plotly.pyi b/reflex/components/plotly/plotly.pyi
index 7c8068e1e..186b78a68 100644
--- a/reflex/components/plotly/plotly.pyi
+++ b/reflex/components/plotly/plotly.pyi
@@ -1,108 +1,43 @@
"""Stub file for reflex/components/plotly/plotly.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Any, Dict, List
+from reflex.base import Base
from reflex.components.component import NoSSRComponent
-from reflex.vars import Var
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.utils import console
+from reflex.vars.base import Var
try:
- from plotly.graph_objects import Figure # type: ignore
+ from plotly.graph_objects import Figure, layout
+
+ Template = layout.Template
except ImportError:
- Figure = Any # type: ignore
+ console.warn("Plotly is not installed. Please run `pip install plotly`.")
+ Figure = Any
+ Template = Any
-class PlotlyLib(NoSSRComponent):
+class _ButtonClickData(Base):
+ menu: Any
+ button: Any
+ active: Any
+
+class Plotly(NoSSRComponent):
+ def add_imports(self) -> dict[str, str]: ...
+ def add_custom_code(self) -> list[str]: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- style: Optional[Style] = None,
- key: Optional[Any] = None,
- id: Optional[Any] = None,
- class_name: Optional[Any] = None,
- autofocus: Optional[bool] = None,
- custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
- ) -> "PlotlyLib":
- """Create the component.
-
- Args:
- *children: The children of the component.
- style: The style of the component.
- key: A unique key for the component.
- id: The id for the component.
- class_name: The class name for the component.
- autofocus: Whether the component should take the focus once the page is loaded
- custom_attrs: custom attribute
- **props: The props of the component.
-
- Returns:
- The component.
- """
- ...
-
-class Plotly(PlotlyLib):
- @overload
- @classmethod
- def create( # type: ignore
- cls,
- *children,
- data: Optional[Union[Var[Figure], Figure]] = None, # type: ignore
- layout: Optional[Union[Var[Dict], Dict]] = None,
- config: Optional[Union[Var[Dict], Dict]] = None,
- width: Optional[Union[Var[str], str]] = None,
- height: Optional[Union[Var[str], str]] = None,
+ data: Optional[Union[Figure, Var[Figure]]] = None, # type: ignore
+ layout: Optional[Union[Dict, Var[Dict]]] = None,
+ template: Optional[Union[Template, Var[Template]]] = None, # type: ignore
+ config: Optional[Union[Dict, Var[Dict]]] = None,
use_resize_handler: Optional[Union[Var[bool], bool]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
@@ -110,72 +45,79 @@ class Plotly(PlotlyLib):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_after_plot: Optional[EventType] = None,
+ on_animated: Optional[EventType] = None,
+ on_animating_frame: Optional[EventType] = None,
+ on_animation_interrupted: Optional[EventType] = None,
+ on_autosize: Optional[EventType] = None,
+ on_before_hover: Optional[EventType] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_button_clicked: Optional[EventType] = None,
+ on_click: Optional[EventType] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_deselect: Optional[EventType] = None,
+ on_double_click: Optional[EventType] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_hover: Optional[EventType] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_redraw: Optional[EventType] = None,
+ on_relayout: Optional[EventType] = None,
+ on_relayouting: Optional[EventType] = None,
+ on_restyle: Optional[EventType] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_selected: Optional[EventType] = None,
+ on_selecting: Optional[EventType] = None,
+ on_transition_interrupted: Optional[EventType] = None,
+ on_transitioning: Optional[EventType] = None,
+ on_unhover: Optional[EventType] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Plotly":
- """Create the component.
+ """Create the Plotly component.
Args:
*children: The children of the component.
data: The figure to display. This can be a plotly figure or a plotly data json.
layout: The layout of the graph.
+ template: The template for visual appearance of the graph.
config: The config of the graph.
- width: The width of the graph.
- height: The height of the graph.
use_resize_handler: If true, the graph will resize when the window is resized.
+ on_after_plot: Fired after the plot is redrawn.
+ on_animated: Fired after the plot was animated.
+ on_animating_frame: Fired while animating a single frame (does not currently pass data through).
+ on_animation_interrupted: Fired when an animation is interrupted (to start a new animation for example).
+ on_autosize: Fired when the plot is responsively sized.
+ on_before_hover: Fired whenever mouse moves over a plot.
+ on_button_clicked: Fired when a plotly UI button is clicked.
+ on_click: Fired when the plot is clicked.
+ on_deselect: Fired when a selection is cleared (via double click).
+ on_double_click: Fired when the plot is double clicked.
+ on_hover: Fired when a plot element is hovered over.
+ on_relayout: Fired after the plot is layed out (zoom, pan, etc).
+ on_relayouting: Fired while the plot is being layed out.
+ on_restyle: Fired after the plot style is changed.
+ on_redraw: Fired after the plot is redrawn.
+ on_selected: Fired after selecting plot elements.
+ on_selecting: Fired while dragging a selection.
+ on_transitioning: Fired while an animation is occuring.
+ on_transition_interrupted: Fired when a transition is stopped early.
+ on_unhover: Fired when a hovered element is no longer hovered.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
class_name: The class name for the component.
autofocus: Whether the component should take the focus once the page is loaded
custom_attrs: custom attribute
- **props: The props of the component.
+ **props: The properties of the component.
Returns:
- The component.
+ The Plotly component.
"""
...
diff --git a/reflex/components/props.py b/reflex/components/props.py
new file mode 100644
index 000000000..adce134fc
--- /dev/null
+++ b/reflex/components/props.py
@@ -0,0 +1,76 @@
+"""A class that holds props to be passed or applied to a component."""
+
+from __future__ import annotations
+
+from pydantic import ValidationError
+
+from reflex.base import Base
+from reflex.utils import format
+from reflex.utils.exceptions import InvalidPropValueError
+from reflex.vars.object import LiteralObjectVar
+
+
+class PropsBase(Base):
+ """Base for a class containing props that can be serialized as a JS object."""
+
+ def json(self) -> str:
+ """Convert the object to a json-like string.
+
+ Vars will be unwrapped so they can represent actual JS var names and functions.
+
+ Keys will be converted to camelCase.
+
+ Returns:
+ The object as a Javascript Object literal.
+ """
+ return LiteralObjectVar.create(
+ {format.to_camel_case(key): value for key, value in self.dict().items()}
+ ).json()
+
+ def dict(self, *args, **kwargs):
+ """Convert the object to a dictionary.
+
+ Keys will be converted to camelCase.
+
+ Args:
+ *args: Arguments to pass to the parent class.
+ **kwargs: Keyword arguments to pass to the parent class.
+
+ Returns:
+ The object as a dictionary.
+ """
+ return {
+ format.to_camel_case(key): value
+ for key, value in super().dict(*args, **kwargs).items()
+ }
+
+
+class NoExtrasAllowedProps(Base):
+ """A class that holds props to be passed or applied to a component with no extra props allowed."""
+
+ def __init__(self, component_name=None, **kwargs):
+ """Initialize the props.
+
+ Args:
+ component_name: The custom name of the component.
+ kwargs: Kwargs to initialize the props.
+
+ Raises:
+ InvalidPropValueError: If invalid props are passed on instantiation.
+ """
+ component_name = component_name or type(self).__name__
+ try:
+ super().__init__(**kwargs)
+ except ValidationError as e:
+ invalid_fields = ", ".join([error["loc"][0] for error in e.errors()]) # type: ignore
+ supported_props_str = ", ".join(f'"{field}"' for field in self.get_fields())
+ raise InvalidPropValueError(
+ f"Invalid prop(s) {invalid_fields} for {component_name!r}. Supported props are {supported_props_str}"
+ ) from None
+
+ class Config:
+ """Pydantic config."""
+
+ arbitrary_types_allowed = True
+ use_enum_values = True
+ extra = "forbid"
diff --git a/reflex/components/radix/__init__.py b/reflex/components/radix/__init__.py
index 08d1dcfef..6b1673b88 100644
--- a/reflex/components/radix/__init__.py
+++ b/reflex/components/radix/__init__.py
@@ -1,4 +1,17 @@
"""Namespace for components provided by @radix-ui packages."""
-from .primitives import *
-from .themes import *
+from __future__ import annotations
+
+from reflex import RADIX_MAPPING
+from reflex.utils import lazy_loader
+
+_SUBMODULES: set[str] = {"themes", "primitives"}
+
+_SUBMOD_ATTRS: dict[str, list[str]] = {
+ "".join(k.split("components.radix.")[-1]): v for k, v in RADIX_MAPPING.items()
+}
+__getattr__, __dir__, __all__ = lazy_loader.attach(
+ __name__,
+ submodules=_SUBMODULES,
+ submod_attrs=_SUBMOD_ATTRS,
+)
diff --git a/reflex/components/radix/__init__.pyi b/reflex/components/radix/__init__.pyi
new file mode 100644
index 000000000..f4e81666a
--- /dev/null
+++ b/reflex/components/radix/__init__.pyi
@@ -0,0 +1,70 @@
+"""Stub file for reflex/components/radix/__init__.py"""
+# ------------------- DO NOT EDIT ----------------------
+# This file was generated by `reflex/utils/pyi_generator.py`!
+# ------------------------------------------------------
+
+from . import primitives as primitives
+from . import themes as themes
+from .primitives.accordion import accordion as accordion
+from .primitives.drawer import drawer as drawer
+from .primitives.form import form as form
+from .themes.base import theme as theme
+from .themes.base import theme_panel as theme_panel
+from .themes.color_mode import color_mode as color_mode
+from .themes.components.alert_dialog import alert_dialog as alert_dialog
+from .themes.components.aspect_ratio import aspect_ratio as aspect_ratio
+from .themes.components.avatar import avatar as avatar
+from .themes.components.badge import badge as badge
+from .themes.components.button import button as button
+from .themes.components.callout import callout as callout
+from .themes.components.card import card as card
+from .themes.components.checkbox import checkbox as checkbox
+from .themes.components.checkbox_cards import checkbox_cards as checkbox_cards
+from .themes.components.checkbox_group import checkbox_group as checkbox_group
+from .themes.components.context_menu import context_menu as context_menu
+from .themes.components.data_list import data_list as data_list
+from .themes.components.dialog import dialog as dialog
+from .themes.components.dropdown_menu import dropdown_menu as dropdown_menu
+from .themes.components.dropdown_menu import menu as menu
+from .themes.components.hover_card import hover_card as hover_card
+from .themes.components.icon_button import icon_button as icon_button
+from .themes.components.inset import inset as inset
+from .themes.components.popover import popover as popover
+from .themes.components.progress import progress as progress
+from .themes.components.radio_cards import radio_cards as radio_cards
+from .themes.components.radio_group import radio as radio
+from .themes.components.radio_group import radio_group as radio_group
+from .themes.components.scroll_area import scroll_area as scroll_area
+from .themes.components.segmented_control import segmented_control as segmented_control
+from .themes.components.select import select as select
+from .themes.components.separator import divider as divider
+from .themes.components.separator import separator as separator
+from .themes.components.skeleton import skeleton as skeleton
+from .themes.components.slider import slider as slider
+from .themes.components.spinner import spinner as spinner
+from .themes.components.switch import switch as switch
+from .themes.components.table import table as table
+from .themes.components.tabs import tabs as tabs
+from .themes.components.text_area import text_area as text_area
+from .themes.components.text_field import input as input
+from .themes.components.text_field import text_field as text_field
+from .themes.components.tooltip import tooltip as tooltip
+from .themes.layout.box import box as box
+from .themes.layout.center import center as center
+from .themes.layout.container import container as container
+from .themes.layout.flex import flex as flex
+from .themes.layout.grid import grid as grid
+from .themes.layout.list import list_item as list_item
+from .themes.layout.list import list_ns as list # noqa
+from .themes.layout.list import ordered_list as ordered_list
+from .themes.layout.list import unordered_list as unordered_list
+from .themes.layout.section import section as section
+from .themes.layout.spacer import spacer as spacer
+from .themes.layout.stack import hstack as hstack
+from .themes.layout.stack import stack as stack
+from .themes.layout.stack import vstack as vstack
+from .themes.typography.blockquote import blockquote as blockquote
+from .themes.typography.code import code as code
+from .themes.typography.heading import heading as heading
+from .themes.typography.link import link as link
+from .themes.typography.text import text as text
diff --git a/reflex/components/radix/primitives/__init__.py b/reflex/components/radix/primitives/__init__.py
index 23070044e..fc45e7e19 100644
--- a/reflex/components/radix/primitives/__init__.py
+++ b/reflex/components/radix/primitives/__init__.py
@@ -1,7 +1,16 @@
"""Radix primitive components (https://www.radix-ui.com/primitives)."""
-from .accordion import accordion
-from .drawer import drawer
-from .form import form
-from .progress import progress
-from .slider import slider
+from __future__ import annotations
+
+from reflex import RADIX_PRIMITIVES_MAPPING
+from reflex.utils import lazy_loader
+
+_SUBMOD_ATTRS: dict[str, list[str]] = {
+ "".join(k.split("components.radix.primitives.")[-1]): v
+ for k, v in RADIX_PRIMITIVES_MAPPING.items()
+}
+
+__getattr__, __dir__, __all__ = lazy_loader.attach(
+ __name__,
+ submod_attrs=_SUBMOD_ATTRS,
+)
diff --git a/reflex/components/radix/primitives/__init__.pyi b/reflex/components/radix/primitives/__init__.pyi
new file mode 100644
index 000000000..e7461e9a7
--- /dev/null
+++ b/reflex/components/radix/primitives/__init__.pyi
@@ -0,0 +1,9 @@
+"""Stub file for reflex/components/radix/primitives/__init__.py"""
+# ------------------- DO NOT EDIT ----------------------
+# This file was generated by `reflex/utils/pyi_generator.py`!
+# ------------------------------------------------------
+
+from .accordion import accordion as accordion
+from .drawer import drawer as drawer
+from .form import form as form
+from .progress import progress as progress
diff --git a/reflex/components/radix/primitives/accordion.py b/reflex/components/radix/primitives/accordion.py
index 9cadfb35d..272274723 100644
--- a/reflex/components/radix/primitives/accordion.py
+++ b/reflex/components/radix/primitives/accordion.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from typing import Any, Dict, List, Literal, Optional, Union
+from typing import Any, List, Literal, Tuple, Union
from reflex.components.component import Component, ComponentNamespace
from reflex.components.core.colors import color
@@ -10,9 +10,10 @@ from reflex.components.core.cond import cond
from reflex.components.lucide.icon import Icon
from reflex.components.radix.primitives.base import RadixPrimitiveComponent
from reflex.components.radix.themes.base import LiteralAccentColor, LiteralRadius
+from reflex.event import EventHandler
from reflex.style import Style
-from reflex.utils import imports
-from reflex.vars import Var, get_uuid_string_var
+from reflex.vars import get_uuid_string_var
+from reflex.vars.base import LiteralVar, Var
LiteralAccordionType = Literal["single", "multiple"]
LiteralAccordionDir = Literal["ltr", "rtl"]
@@ -59,7 +60,7 @@ class AccordionComponent(RadixPrimitiveComponent):
# The variant of the component.
variant: Var[LiteralAccordionVariant]
- def add_style(self) -> Style | None:
+ def add_style(self):
"""Add style to the component."""
if self.color_scheme is not None:
self.custom_attrs["data-accent-color"] = self.color_scheme
@@ -70,6 +71,18 @@ class AccordionComponent(RadixPrimitiveComponent):
return ["color_scheme", "variant"]
+def on_value_change(value: Var[str | List[str]]) -> Tuple[Var[str | List[str]]]:
+ """Handle the on_value_change event.
+
+ Args:
+ value: The value of the event.
+
+ Returns:
+ The value of the event.
+ """
+ return (value,)
+
+
class AccordionRoot(AccordionComponent):
"""An accordion component."""
@@ -102,16 +115,19 @@ class AccordionRoot(AccordionComponent):
radius: Var[LiteralRadius]
# The time in milliseconds to animate open and close
- duration: Var[int] = Var.create_safe(DEFAULT_ANIMATION_DURATION)
+ duration: Var[int] = LiteralVar.create(DEFAULT_ANIMATION_DURATION)
# The easing function to use for the animation.
- easing: Var[str] = Var.create_safe(DEFAULT_ANIMATION_EASING)
+ easing: Var[str] = LiteralVar.create(DEFAULT_ANIMATION_EASING)
# Whether to show divider lines between items.
show_dividers: Var[bool]
_valid_children: List[str] = ["AccordionItem"]
+ # Fired when the opened the accordions changes.
+ on_value_change: EventHandler[on_value_change]
+
def _exclude_props(self) -> list[str]:
return super()._exclude_props() + [
"radius",
@@ -120,17 +136,6 @@ class AccordionRoot(AccordionComponent):
"show_dividers",
]
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
-
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- "on_value_change": lambda e0: [e0],
- }
-
def add_style(self):
"""Add style to the component.
@@ -188,6 +193,11 @@ class AccordionItem(AccordionComponent):
# When true, prevents the user from interacting with the item.
disabled: Var[bool]
+ # The header of the accordion item.
+ header: Var[Union[Component, str]]
+ # The content of the accordion item.
+ content: Var[Union[Component, str]] = Var.create(None)
+
_valid_children: List[str] = [
"AccordionHeader",
"AccordionTrigger",
@@ -200,21 +210,20 @@ class AccordionItem(AccordionComponent):
def create(
cls,
*children,
- header: Optional[Component | Var] = None,
- content: Optional[Component | Var] = None,
**props,
) -> Component:
"""Create an accordion item.
Args:
*children: The list of children to use if header and content are not provided.
- header: The header of the accordion item.
- content: The content of the accordion item.
**props: Additional properties to apply to the accordion item.
Returns:
The accordion item.
"""
+ header = props.pop("header", None)
+ content = props.pop("content", None)
+
# The item requires a value to toggle (use a random unique name if not provided).
value = props.pop("value", get_uuid_string_var())
@@ -250,43 +259,44 @@ class AccordionItem(AccordionComponent):
return super().create(*children, value=value, **props, class_name=cls_name)
- def add_style(self) -> Style | None:
+ def add_style(self) -> dict[str, Any] | None:
"""Add style to the component.
Returns:
The style of the component.
"""
divider_style = f"var(--divider-px) solid {color('gray', 6, alpha=True)}"
- return Style(
- {
- "overflow": "hidden",
- "width": "100%",
- "margin_top": "1px",
+ return {
+ "overflow": "hidden",
+ "width": "100%",
+ "margin_top": "1px",
+ "border_top": divider_style,
+ "&:first-child": {
+ "margin_top": 0,
+ "border_top": 0,
+ "border_top_left_radius": "var(--radius-4)",
+ "border_top_right_radius": "var(--radius-4)",
+ },
+ "&:last-child": {
+ "border_bottom_left_radius": "var(--radius-4)",
+ "border_bottom_right_radius": "var(--radius-4)",
+ },
+ "&:focus-within": {
+ "position": "relative",
+ "z_index": 1,
+ },
+ _inherited_variant_selector("ghost", "&:first-child"): {
+ "border_radius": 0,
"border_top": divider_style,
- "&:first-child": {
- "margin_top": 0,
- "border_top": 0,
- "border_top_left_radius": "var(--radius-4)",
- "border_top_right_radius": "var(--radius-4)",
- },
- "&:last-child": {
- "border_bottom_left_radius": "var(--radius-4)",
- "border_bottom_right_radius": "var(--radius-4)",
- },
- "&:focus-within": {
- "position": "relative",
- "z_index": 1,
- },
- _inherited_variant_selector("ghost", "&:first-child"): {
- "border_radius": 0,
- "border_top": divider_style,
- },
- _inherited_variant_selector("ghost", "&:last-child"): {
- "border_radius": 0,
- "border_bottom": divider_style,
- },
- }
- )
+ },
+ _inherited_variant_selector("ghost", "&:last-child"): {
+ "border_radius": 0,
+ "border_bottom": divider_style,
+ },
+ }
+
+ def _exclude_props(self) -> list[str]:
+ return ["header", "content"]
class AccordionHeader(AccordionComponent):
@@ -314,13 +324,13 @@ class AccordionHeader(AccordionComponent):
return super().create(*children, class_name=cls_name, **props)
- def add_style(self) -> Style | None:
+ def add_style(self) -> dict[str, Any] | None:
"""Add style to the component.
Returns:
The style of the component.
"""
- return Style({"display": "flex"})
+ return {"display": "flex"}
class AccordionTrigger(AccordionComponent):
@@ -348,44 +358,42 @@ class AccordionTrigger(AccordionComponent):
return super().create(*children, class_name=cls_name, **props)
- def add_style(self) -> Style | None:
+ def add_style(self) -> dict[str, Any] | None:
"""Add style to the component.
Returns:
The style of the component.
"""
- return Style(
- {
- "color": color("accent", 11),
- "font_size": "1.1em",
- "line_height": 1,
- "justify_content": "space-between",
- "align_items": "center",
- "flex": 1,
- "display": "flex",
- "padding": "var(--space-3) var(--space-4)",
- "width": "100%",
- "box_shadow": f"0 var(--divider-px) 0 {color('gray', 6, alpha=True)}",
- "&[data-state='open'] > .AccordionChevron": {
- "transform": "rotate(180deg)",
- },
+ return {
+ "color": color("accent", 11),
+ "font_size": "1.1em",
+ "line_height": 1,
+ "justify_content": "space-between",
+ "align_items": "center",
+ "flex": 1,
+ "display": "flex",
+ "padding": "var(--space-3) var(--space-4)",
+ "width": "100%",
+ "box_shadow": f"0 var(--divider-px) 0 {color('gray', 6, alpha=True)}",
+ "&[data-state='open'] > .AccordionChevron": {
+ "transform": "rotate(180deg)",
+ },
+ "&:hover": {
+ "background_color": color("accent", 4),
+ },
+ "& > .AccordionChevron": {
+ "transition": f"transform var(--animation-duration) var(--animation-easing)",
+ },
+ _inherited_variant_selector("classic"): {
+ "color": "var(--accent-contrast)",
"&:hover": {
- "background_color": color("accent", 4),
+ "background_color": color("accent", 10),
},
"& > .AccordionChevron": {
- "transition": f"transform var(--animation-duration) var(--animation-easing)",
- },
- _inherited_variant_selector("classic"): {
"color": "var(--accent-contrast)",
- "&:hover": {
- "background_color": color("accent", 10),
- },
- "& > .AccordionChevron": {
- "color": "var(--accent-contrast)",
- },
},
- }
- )
+ },
+ }
class AccordionIcon(Icon):
@@ -417,13 +425,13 @@ class AccordionContent(AccordionComponent):
alias = "RadixAccordionContent"
- def add_imports(self) -> imports.ImportDict:
+ def add_imports(self) -> dict:
"""Add imports to the component.
Returns:
The imports of the component.
"""
- return {"@emotion/react": [imports.ImportVar(tag="keyframes")]}
+ return {"@emotion/react": "keyframes"}
@classmethod
def create(cls, *children, **props) -> Component:
@@ -470,40 +478,36 @@ to {
"""
]
- def add_style(self) -> Style | None:
+ def add_style(self) -> dict[str, Any] | None:
"""Add style to the component.
Returns:
The style of the component.
"""
- slideDown = Var.create(
+ slideDown = LiteralVar.create(
f"${{slideDown}} var(--animation-duration) var(--animation-easing)",
- _var_is_string=True,
)
- slideUp = Var.create(
+ slideUp = LiteralVar.create(
f"${{slideUp}} var(--animation-duration) var(--animation-easing)",
- _var_is_string=True,
)
- return Style(
- {
- "overflow": "hidden",
- "color": color("accent", 11),
- "padding_x": "var(--space-4)",
- # Apply before and after content to avoid height animation jank.
- "&:before, &:after": {
- "content": "' '",
- "display": "block",
- "height": "var(--space-3)",
- },
- "&[data-state='open']": {"animation": slideDown},
- "&[data-state='closed']": {"animation": slideUp},
- _inherited_variant_selector("classic"): {
- "color": "var(--accent-contrast)",
- },
- }
- )
+ return {
+ "overflow": "hidden",
+ "color": color("accent", 11),
+ "padding_x": "var(--space-4)",
+ # Apply before and after content to avoid height animation jank.
+ "&:before, &:after": {
+ "content": "' '",
+ "display": "block",
+ "height": "var(--space-3)",
+ },
+ "&[data-state='open']": {"animation": slideDown},
+ "&[data-state='closed']": {"animation": slideUp},
+ _inherited_variant_selector("classic"): {
+ "color": "var(--accent-contrast)",
+ },
+ }
class Accordion(ComponentNamespace):
diff --git a/reflex/components/radix/primitives/accordion.pyi b/reflex/components/radix/primitives/accordion.pyi
index e7ae3ff19..c0047442b 100644
--- a/reflex/components/radix/primitives/accordion.pyi
+++ b/reflex/components/radix/primitives/accordion.pyi
@@ -1,22 +1,16 @@
"""Stub file for reflex/components/radix/primitives/accordion.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, List, Literal, Optional, Tuple, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Any, Dict, List, Literal, Optional, Union
from reflex.components.component import Component, ComponentNamespace
-from reflex.components.core.colors import color
-from reflex.components.core.cond import cond
from reflex.components.lucide.icon import Icon
from reflex.components.radix.primitives.base import RadixPrimitiveComponent
-from reflex.components.radix.themes.base import LiteralAccentColor, LiteralRadius
+from reflex.event import EventType
from reflex.style import Style
-from reflex.utils import imports
-from reflex.vars import Var, get_uuid_string_var
+from reflex.vars.base import Var
LiteralAccordionType = Literal["single", "multiple"]
LiteralAccordionDir = Literal["ltr", "rtl"]
@@ -26,7 +20,7 @@ DEFAULT_ANIMATION_DURATION = 250
DEFAULT_ANIMATION_EASING = "cubic-bezier(0.87, 0, 0.13, 1)"
class AccordionComponent(RadixPrimitiveComponent):
- def add_style(self) -> Style | None: ...
+ def add_style(self): ...
@overload
@classmethod
def create( # type: ignore
@@ -34,70 +28,70 @@ class AccordionComponent(RadixPrimitiveComponent):
*children,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
variant: Optional[
Union[
- Var[Literal["classic", "soft", "surface", "outline", "ghost"]],
- Literal["classic", "soft", "surface", "outline", "ghost"],
+ Literal["classic", "ghost", "outline", "soft", "surface"],
+ Var[Literal["classic", "ghost", "outline", "soft", "surface"]],
]
] = None,
as_child: Optional[Union[Var[bool], bool]] = None,
@@ -107,52 +101,22 @@ class AccordionComponent(RadixPrimitiveComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "AccordionComponent":
"""Create the component.
@@ -174,8 +138,9 @@ class AccordionComponent(RadixPrimitiveComponent):
"""
...
+def on_value_change(value: Var[str | List[str]]) -> Tuple[Var[str | List[str]]]: ...
+
class AccordionRoot(AccordionComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
def add_style(self): ...
@overload
@classmethod
@@ -183,27 +148,25 @@ class AccordionRoot(AccordionComponent):
cls,
*children,
type: Optional[
- Union[Var[Literal["single", "multiple"]], Literal["single", "multiple"]]
- ] = None,
- value: Optional[
- Union[Var[Union[str, List[str]]], Union[str, List[str]]]
+ Union[Literal["multiple", "single"], Var[Literal["multiple", "single"]]]
] = None,
+ value: Optional[Union[List[str], Var[Union[List[str], str]], str]] = None,
default_value: Optional[
- Union[Var[Union[str, List[str]]], Union[str, List[str]]]
+ Union[List[str], Var[Union[List[str], str]], str]
] = None,
collapsible: Optional[Union[Var[bool], bool]] = None,
disabled: Optional[Union[Var[bool], bool]] = None,
- dir: Optional[Union[Var[Literal["ltr", "rtl"]], Literal["ltr", "rtl"]]] = None,
+ dir: Optional[Union[Literal["ltr", "rtl"], Var[Literal["ltr", "rtl"]]]] = None,
orientation: Optional[
Union[
- Var[Literal["vertical", "horizontal"]],
- Literal["vertical", "horizontal"],
+ Literal["horizontal", "vertical"],
+ Var[Literal["horizontal", "vertical"]],
]
] = None,
radius: Optional[
Union[
- Var[Literal["none", "small", "medium", "large", "full"]],
- Literal["none", "small", "medium", "large", "full"],
+ Literal["full", "large", "medium", "none", "small"],
+ Var[Literal["full", "large", "medium", "none", "small"]],
]
] = None,
duration: Optional[Union[Var[int], int]] = None,
@@ -211,70 +174,70 @@ class AccordionRoot(AccordionComponent):
show_dividers: Optional[Union[Var[bool], bool]] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
variant: Optional[
Union[
- Var[Literal["classic", "soft", "surface", "outline", "ghost"]],
- Literal["classic", "soft", "surface", "outline", "ghost"],
+ Literal["classic", "ghost", "outline", "soft", "surface"],
+ Var[Literal["classic", "ghost", "outline", "soft", "surface"]],
]
] = None,
as_child: Optional[Union[Var[bool], bool]] = None,
@@ -284,55 +247,23 @@ class AccordionRoot(AccordionComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_value_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ on_value_change: Optional[EventType[str | List[str]]] = None,
+ **props,
) -> "AccordionRoot":
"""Create the component.
@@ -349,6 +280,7 @@ class AccordionRoot(AccordionComponent):
duration: The time in milliseconds to animate open and close
easing: The easing function to use for the animation.
show_dividers: Whether to show divider lines between items.
+ on_value_change: Fired when the opened the accordions changes.
color_scheme: The color scheme of the component.
variant: The variant of the component.
as_child: Change the default rendered element for the one passed as a child.
@@ -371,76 +303,76 @@ class AccordionItem(AccordionComponent):
def create( # type: ignore
cls,
*children,
- header: Optional[Union[Component, Var]] = None,
- content: Optional[Union[Component, Var]] = None,
value: Optional[Union[Var[str], str]] = None,
disabled: Optional[Union[Var[bool], bool]] = None,
+ header: Optional[Union[Component, Var[Union[Component, str]], str]] = None,
+ content: Optional[Union[Component, Var[Union[Component, str]], str]] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
variant: Optional[
Union[
- Var[Literal["classic", "soft", "surface", "outline", "ghost"]],
- Literal["classic", "soft", "surface", "outline", "ghost"],
+ Literal["classic", "ghost", "outline", "soft", "surface"],
+ Var[Literal["classic", "ghost", "outline", "soft", "surface"]],
]
] = None,
as_child: Optional[Union[Var[bool], bool]] = None,
@@ -450,61 +382,31 @@ class AccordionItem(AccordionComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "AccordionItem":
"""Create an accordion item.
Args:
*children: The list of children to use if header and content are not provided.
- header: The header of the accordion item.
- content: The content of the accordion item.
value: A unique identifier for the item.
disabled: When true, prevents the user from interacting with the item.
+ header: The header of the accordion item.
+ content: The content of the accordion item.
color_scheme: The color scheme of the component.
variant: The variant of the component.
as_child: Change the default rendered element for the one passed as a child.
@@ -520,7 +422,8 @@ class AccordionItem(AccordionComponent):
The accordion item.
"""
...
- def add_style(self) -> Style | None: ...
+
+ def add_style(self) -> dict[str, Any] | None: ...
class AccordionHeader(AccordionComponent):
@overload
@@ -530,70 +433,70 @@ class AccordionHeader(AccordionComponent):
*children,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
variant: Optional[
Union[
- Var[Literal["classic", "soft", "surface", "outline", "ghost"]],
- Literal["classic", "soft", "surface", "outline", "ghost"],
+ Literal["classic", "ghost", "outline", "soft", "surface"],
+ Var[Literal["classic", "ghost", "outline", "soft", "surface"]],
]
] = None,
as_child: Optional[Union[Var[bool], bool]] = None,
@@ -603,52 +506,22 @@ class AccordionHeader(AccordionComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "AccordionHeader":
"""Create the Accordion header component.
@@ -669,7 +542,8 @@ class AccordionHeader(AccordionComponent):
The Accordion header Component.
"""
...
- def add_style(self) -> Style | None: ...
+
+ def add_style(self) -> dict[str, Any] | None: ...
class AccordionTrigger(AccordionComponent):
@overload
@@ -679,70 +553,70 @@ class AccordionTrigger(AccordionComponent):
*children,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
variant: Optional[
Union[
- Var[Literal["classic", "soft", "surface", "outline", "ghost"]],
- Literal["classic", "soft", "surface", "outline", "ghost"],
+ Literal["classic", "ghost", "outline", "soft", "surface"],
+ Var[Literal["classic", "ghost", "outline", "soft", "surface"]],
]
] = None,
as_child: Optional[Union[Var[bool], bool]] = None,
@@ -752,52 +626,22 @@ class AccordionTrigger(AccordionComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "AccordionTrigger":
"""Create the Accordion trigger component.
@@ -818,7 +662,8 @@ class AccordionTrigger(AccordionComponent):
The Accordion trigger Component.
"""
...
- def add_style(self) -> Style | None: ...
+
+ def add_style(self) -> dict[str, Any] | None: ...
class AccordionIcon(Icon):
@overload
@@ -833,52 +678,22 @@ class AccordionIcon(Icon):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "AccordionIcon":
"""Create the Accordion icon component.
@@ -899,7 +714,7 @@ class AccordionIcon(Icon):
...
class AccordionContent(AccordionComponent):
- def add_imports(self) -> imports.ImportDict: ...
+ def add_imports(self) -> dict: ...
@overload
@classmethod
def create( # type: ignore
@@ -907,70 +722,70 @@ class AccordionContent(AccordionComponent):
*children,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
variant: Optional[
Union[
- Var[Literal["classic", "soft", "surface", "outline", "ghost"]],
- Literal["classic", "soft", "surface", "outline", "ghost"],
+ Literal["classic", "ghost", "outline", "soft", "surface"],
+ Var[Literal["classic", "ghost", "outline", "soft", "surface"]],
]
] = None,
as_child: Optional[Union[Var[bool], bool]] = None,
@@ -980,52 +795,22 @@ class AccordionContent(AccordionComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "AccordionContent":
"""Create the Accordion content component.
@@ -1046,8 +831,9 @@ class AccordionContent(AccordionComponent):
The Accordion content Component.
"""
...
+
def add_custom_code(self) -> list[str]: ...
- def add_style(self) -> Style | None: ...
+ def add_style(self) -> dict[str, Any] | None: ...
class Accordion(ComponentNamespace):
content = staticmethod(AccordionContent.create)
diff --git a/reflex/components/radix/primitives/base.py b/reflex/components/radix/primitives/base.py
index bd1690c3b..479cd2912 100644
--- a/reflex/components/radix/primitives/base.py
+++ b/reflex/components/radix/primitives/base.py
@@ -1,10 +1,11 @@
"""The base component for Radix primitives."""
+
from typing import List
from reflex.components.component import Component
from reflex.components.tags.tag import Tag
from reflex.utils import format
-from reflex.vars import Var
+from reflex.vars.base import Var
class RadixPrimitiveComponent(Component):
@@ -25,7 +26,7 @@ class RadixPrimitiveComponentWithClassName(RadixPrimitiveComponent):
._render()
.add_props(
**{
- "class_name": format.to_title_case(self.tag or ""),
+ "class_name": f"{format.to_title_case(self.tag or '')} {self.class_name or ''}",
}
)
)
diff --git a/reflex/components/radix/primitives/base.pyi b/reflex/components/radix/primitives/base.pyi
index 7dbdbcbea..3eacd3f07 100644
--- a/reflex/components/radix/primitives/base.pyi
+++ b/reflex/components/radix/primitives/base.pyi
@@ -1,17 +1,14 @@
"""Stub file for reflex/components/radix/primitives/base.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import List
from reflex.components.component import Component
-from reflex.components.tags.tag import Tag
-from reflex.utils import format
-from reflex.vars import Var
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
class RadixPrimitiveComponent(Component):
@overload
@@ -26,52 +23,22 @@ class RadixPrimitiveComponent(Component):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "RadixPrimitiveComponent":
"""Create the component.
@@ -104,52 +71,22 @@ class RadixPrimitiveComponentWithClassName(RadixPrimitiveComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "RadixPrimitiveComponentWithClassName":
"""Create the component.
diff --git a/reflex/components/radix/primitives/drawer.py b/reflex/components/radix/primitives/drawer.py
index a4e582b02..d478dc171 100644
--- a/reflex/components/radix/primitives/drawer.py
+++ b/reflex/components/radix/primitives/drawer.py
@@ -4,14 +4,15 @@
# Style based on https://ui.shadcn.com/docs/components/drawer
from __future__ import annotations
-from typing import Any, Dict, List, Literal, Optional, Union
+from typing import Any, List, Literal, Optional, Union
from reflex.components.component import Component, ComponentNamespace
from reflex.components.radix.primitives.base import RadixPrimitiveComponent
from reflex.components.radix.themes.base import Theme
from reflex.components.radix.themes.layout.flex import Flex
-from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.event import EventHandler, empty_event, identity_event
+from reflex.utils import console
+from reflex.vars.base import Var
class DrawerComponent(RadixPrimitiveComponent):
@@ -59,16 +60,8 @@ class DrawerRoot(DrawerComponent):
# When `True`, it prevents scroll restoration. Defaults to `True`.
preventScrollRestoration: Var[bool]
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the event triggers that pass the component's value to the handler.
-
- Returns:
- A dict mapping the event trigger to the var that is passed to the handler.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_OPEN_CHANGE: lambda e0: [e0],
- }
+ # Fires when the drawer is opened or closed.
+ on_open_change: EventHandler[identity_event(bool)]
class DrawerTrigger(DrawerComponent):
@@ -86,8 +79,8 @@ class DrawerTrigger(DrawerComponent):
"""Create a new DrawerTrigger instance.
Args:
- children: The children of the element.
- props: The properties of the element.
+ *children: The children of the element.
+ **props: The properties of the element.
Returns:
The new DrawerTrigger instance.
@@ -135,22 +128,20 @@ class DrawerContent(DrawerComponent):
base_style.update(style)
return {"css": base_style}
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
+ # Fired when the drawer content is opened. Deprecated.
+ on_open_auto_focus: EventHandler[empty_event]
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- # DrawerContent is based on Radix DialogContent
- # These are the same triggers as DialogContent
- EventTriggers.ON_OPEN_AUTO_FOCUS: lambda e0: [e0.target.value],
- EventTriggers.ON_CLOSE_AUTO_FOCUS: lambda e0: [e0.target.value],
- EventTriggers.ON_ESCAPE_KEY_DOWN: lambda e0: [e0.target.value],
- EventTriggers.ON_POINTER_DOWN_OUTSIDE: lambda e0: [e0.target.value],
- EventTriggers.ON_INTERACT_OUTSIDE: lambda e0: [e0.target.value],
- }
+ # Fired when the drawer content is closed. Deprecated.
+ on_close_auto_focus: EventHandler[empty_event]
+
+ # Fired when the escape key is pressed. Deprecated.
+ on_escape_key_down: EventHandler[empty_event]
+
+ # Fired when the pointer is down outside the drawer content. Deprecated.
+ on_pointer_down_outside: EventHandler[empty_event]
+
+ # Fired when interacting outside the drawer content. Deprecated.
+ on_interact_outside: EventHandler[empty_event]
@classmethod
def create(cls, *children, **props):
@@ -167,6 +158,23 @@ class DrawerContent(DrawerComponent):
Returns:
The drawer content.
"""
+ deprecated_properties = [
+ "on_open_auto_focus",
+ "on_close_auto_focus",
+ "on_escape_key_down",
+ "on_pointer_down_outside",
+ "on_interact_outside",
+ ]
+
+ for prop in deprecated_properties:
+ if prop in props:
+ console.deprecate(
+ feature_name="drawer content events",
+ reason=f"The `{prop}` event is deprecated and will be removed in 0.7.0.",
+ deprecation_version="0.6.3",
+ removal_version="0.7.0",
+ )
+
comp = super().create(*children, **props)
return Theme.create(comp)
diff --git a/reflex/components/radix/primitives/drawer.pyi b/reflex/components/radix/primitives/drawer.pyi
index de48f8b86..ea2dd8dcf 100644
--- a/reflex/components/radix/primitives/drawer.pyi
+++ b/reflex/components/radix/primitives/drawer.pyi
@@ -1,19 +1,15 @@
"""Stub file for reflex/components/radix/primitives/drawer.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, List, Literal, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Any, Dict, List, Literal, Optional, Union
-from reflex.components.component import Component, ComponentNamespace
+from reflex.components.component import ComponentNamespace
from reflex.components.radix.primitives.base import RadixPrimitiveComponent
-from reflex.components.radix.themes.base import Theme
-from reflex.components.radix.themes.layout.flex import Flex
-from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
class DrawerComponent(RadixPrimitiveComponent):
@overload
@@ -28,52 +24,22 @@ class DrawerComponent(RadixPrimitiveComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DrawerComponent":
"""Create the component.
@@ -96,7 +62,6 @@ class DrawerComponent(RadixPrimitiveComponent):
LiteralDirectionType = Literal["top", "bottom", "left", "right"]
class DrawerRoot(DrawerComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
@@ -105,14 +70,14 @@ class DrawerRoot(DrawerComponent):
open: Optional[Union[Var[bool], bool]] = None,
should_scale_background: Optional[Union[Var[bool], bool]] = None,
close_threshold: Optional[Union[Var[float], float]] = None,
- snap_points: Optional[List[Union[str, float]]] = None,
+ snap_points: Optional[List[Union[float, str]]] = None,
fade_from_index: Optional[Union[Var[int], int]] = None,
scroll_lock_timeout: Optional[Union[Var[int], int]] = None,
modal: Optional[Union[Var[bool], bool]] = None,
direction: Optional[
Union[
- Var[Literal["top", "bottom", "left", "right"]],
- Literal["top", "bottom", "left", "right"],
+ Literal["bottom", "left", "right", "top"],
+ Var[Literal["bottom", "left", "right", "top"]],
]
] = None,
preventScrollRestoration: Optional[Union[Var[bool], bool]] = None,
@@ -123,55 +88,23 @@ class DrawerRoot(DrawerComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_open_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_open_change: Optional[EventType[bool]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DrawerRoot":
"""Create the component.
@@ -186,6 +119,7 @@ class DrawerRoot(DrawerComponent):
modal: When `False`, it allows to interact with elements outside of the drawer without closing it. Defaults to `True`.
direction: Direction of the drawer. Defaults to `"bottom"`
preventScrollRestoration: When `True`, it prevents scroll restoration. Defaults to `True`.
+ on_open_change: Fires when the drawer is opened or closed.
as_child: Change the default rendered element for the one passed as a child.
style: The style of the component.
key: A unique key for the component.
@@ -213,58 +147,35 @@ class DrawerTrigger(DrawerComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DrawerTrigger":
"""Create a new DrawerTrigger instance.
Args:
- children: The children of the element.
- props: The properties of the element.
+ *children: The children of the element.
+ as_child: Change the default rendered element for the one passed as a child.
+ style: The style of the component.
+ key: A unique key for the component.
+ id: The id for the component.
+ class_name: The class name for the component.
+ autofocus: Whether the component should take the focus once the page is loaded
+ custom_attrs: custom attribute
+ **props: The properties of the element.
Returns:
The new DrawerTrigger instance.
@@ -284,52 +195,22 @@ class DrawerPortal(DrawerComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DrawerPortal":
"""Create the component.
@@ -350,7 +231,6 @@ class DrawerPortal(DrawerComponent):
...
class DrawerContent(DrawerComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
@@ -363,67 +243,27 @@ class DrawerContent(DrawerComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_close_auto_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_escape_key_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_interact_outside: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_open_auto_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_pointer_down_outside: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_close_auto_focus: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_escape_key_down: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_interact_outside: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_open_auto_focus: Optional[EventType[[]]] = None,
+ on_pointer_down_outside: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DrawerContent":
"""Create a Drawer Content.
We wrap the Drawer content in an `rx.theme` to make radix themes definitions available to
@@ -460,52 +300,22 @@ class DrawerOverlay(DrawerComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DrawerOverlay":
"""Create the component.
@@ -538,58 +348,35 @@ class DrawerClose(DrawerTrigger):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DrawerClose":
"""Create a new DrawerTrigger instance.
Args:
- children: The children of the element.
- props: The properties of the element.
+ *children: The children of the element.
+ as_child: Change the default rendered element for the one passed as a child.
+ style: The style of the component.
+ key: A unique key for the component.
+ id: The id for the component.
+ class_name: The class name for the component.
+ autofocus: Whether the component should take the focus once the page is loaded
+ custom_attrs: custom attribute
+ **props: The properties of the element.
Returns:
The new DrawerTrigger instance.
@@ -609,52 +396,22 @@ class DrawerTitle(DrawerComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DrawerTitle":
"""Create the component.
@@ -687,52 +444,22 @@ class DrawerDescription(DrawerComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DrawerDescription":
"""Create the component.
@@ -768,14 +495,14 @@ class Drawer(ComponentNamespace):
open: Optional[Union[Var[bool], bool]] = None,
should_scale_background: Optional[Union[Var[bool], bool]] = None,
close_threshold: Optional[Union[Var[float], float]] = None,
- snap_points: Optional[List[Union[str, float]]] = None,
+ snap_points: Optional[List[Union[float, str]]] = None,
fade_from_index: Optional[Union[Var[int], int]] = None,
scroll_lock_timeout: Optional[Union[Var[int], int]] = None,
modal: Optional[Union[Var[bool], bool]] = None,
direction: Optional[
Union[
- Var[Literal["top", "bottom", "left", "right"]],
- Literal["top", "bottom", "left", "right"],
+ Literal["bottom", "left", "right", "top"],
+ Var[Literal["bottom", "left", "right", "top"]],
]
] = None,
preventScrollRestoration: Optional[Union[Var[bool], bool]] = None,
@@ -786,55 +513,23 @@ class Drawer(ComponentNamespace):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_open_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_open_change: Optional[EventType[bool]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DrawerRoot":
"""Create the component.
@@ -849,6 +544,7 @@ class Drawer(ComponentNamespace):
modal: When `False`, it allows to interact with elements outside of the drawer without closing it. Defaults to `True`.
direction: Direction of the drawer. Defaults to `"bottom"`
preventScrollRestoration: When `True`, it prevents scroll restoration. Defaults to `True`.
+ on_open_change: Fires when the drawer is opened or closed.
as_child: Change the default rendered element for the one passed as a child.
style: The style of the component.
key: A unique key for the component.
diff --git a/reflex/components/radix/primitives/form.py b/reflex/components/radix/primitives/form.py
index 3369673da..4d4be7e40 100644
--- a/reflex/components/radix/primitives/form.py
+++ b/reflex/components/radix/primitives/form.py
@@ -2,14 +2,14 @@
from __future__ import annotations
-from typing import Any, Dict, Literal
+from typing import Any, Literal
from reflex.components.component import ComponentNamespace
+from reflex.components.core.debounce import DebounceInput
from reflex.components.el.elements.forms import Form as HTMLForm
from reflex.components.radix.themes.components.text_field import TextFieldRoot
-from reflex.constants.event import EventTriggers
-from reflex.style import Style
-from reflex.vars import Var
+from reflex.event import EventHandler, empty_event
+from reflex.vars.base import Var
from .base import RadixPrimitiveComponentWithClassName
@@ -17,7 +17,7 @@ from .base import RadixPrimitiveComponentWithClassName
class FormComponent(RadixPrimitiveComponentWithClassName):
"""Base class for all @radix-ui/react-form components."""
- library = "@radix-ui/react-form@^0.0.3"
+ library = "@radix-ui/react-form@^0.1.0"
class FormRoot(FormComponent, HTMLForm):
@@ -27,24 +27,16 @@ class FormRoot(FormComponent, HTMLForm):
alias = "RadixFormRoot"
- def get_event_triggers(self) -> Dict[str, Any]:
- """Event triggers for radix form root.
+ # Fired when the errors are cleared.
+ on_clear_server_errors: EventHandler[empty_event]
- Returns:
- The triggers for event supported by Root.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_CLEAR_SERVER_ERRORS: lambda: [],
- }
-
- def add_style(self) -> Style | None:
+ def add_style(self) -> dict[str, Any] | None:
"""Add style to the component.
Returns:
The style of the component.
"""
- return Style({"width": "100%"})
+ return {"width": "100%"}
class FormField(FormComponent):
@@ -60,13 +52,13 @@ class FormField(FormComponent):
# Flag to mark the form field as invalid, for server side validation.
server_invalid: Var[bool]
- def add_style(self) -> Style | None:
+ def add_style(self) -> dict[str, Any] | None:
"""Add style to the component.
Returns:
The style of the component.
"""
- return Style({"display": "grid", "margin_bottom": "10px"})
+ return {"display": "grid", "margin_bottom": "10px"}
class FormLabel(FormComponent):
@@ -76,13 +68,13 @@ class FormLabel(FormComponent):
alias = "RadixFormLabel"
- def add_style(self) -> Style | None:
+ def add_style(self) -> dict[str, Any] | None:
"""Add style to the component.
Returns:
The style of the component.
"""
- return Style({"font_size": "15px", "font_weight": "500", "line_height": "35px"})
+ return {"font_size": "15px", "font_weight": "500", "line_height": "35px"}
class FormControl(FormComponent):
@@ -112,9 +104,9 @@ class FormControl(FormComponent):
f"FormControl can only have at most one child, got {len(children)} children"
)
for child in children:
- if not isinstance(child, TextFieldRoot):
+ if not isinstance(child, (TextFieldRoot, DebounceInput)):
raise TypeError(
- "Only Radix TextFieldRoot is allowed as child of FormControl"
+ "Only Radix TextFieldRoot and DebounceInput are allowed as children of FormControl"
)
return super().create(*children, **props)
@@ -149,13 +141,13 @@ class FormMessage(FormComponent):
# Forces the message to be shown. This is useful when using server-side validation.
force_match: Var[bool]
- def add_style(self) -> Style | None:
+ def add_style(self) -> dict[str, Any] | None:
"""Add style to the component.
Returns:
The style of the component.
"""
- return Style({"font_size": "13px", "opacity": "0.8", "color": "white"})
+ return {"font_size": "13px", "opacity": "0.8", "color": "white"}
class FormValidityState(FormComponent):
diff --git a/reflex/components/radix/primitives/form.pyi b/reflex/components/radix/primitives/form.pyi
index 8e1631825..72595a933 100644
--- a/reflex/components/radix/primitives/form.pyi
+++ b/reflex/components/radix/primitives/form.pyi
@@ -1,19 +1,16 @@
"""Stub file for reflex/components/radix/primitives/form.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Any, Dict, Literal
+
from reflex.components.component import ComponentNamespace
from reflex.components.el.elements.forms import Form as HTMLForm
-from reflex.components.radix.themes.components.text_field import TextFieldRoot
-from reflex.constants.event import EventTriggers
+from reflex.event import EventType
from reflex.style import Style
-from reflex.vars import Var
+from reflex.vars.base import Var
+
from .base import RadixPrimitiveComponentWithClassName
class FormComponent(RadixPrimitiveComponentWithClassName):
@@ -29,52 +26,22 @@ class FormComponent(RadixPrimitiveComponentWithClassName):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "FormComponent":
"""Create the component.
@@ -95,144 +62,84 @@ class FormComponent(RadixPrimitiveComponentWithClassName):
...
class FormRoot(FormComponent, HTMLForm):
- def get_event_triggers(self) -> Dict[str, Any]: ...
- def add_style(self) -> Style | None: ...
+ def add_style(self) -> dict[str, Any] | None: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
as_child: Optional[Union[Var[bool], bool]] = None,
- accept: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ accept: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
accept_charset: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- action: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ action: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_complete: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- enc_type: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- method: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- name: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- no_validate: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- target: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ enc_type: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ method: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ name: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ no_validate: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ target: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
reset_on_submit: Optional[Union[Var[bool], bool]] = None,
handle_submit_unique_name: Optional[Union[Var[str], str]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_clear_server_errors: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_clear_server_errors: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
on_submit: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
+ Union[EventType[Dict[str, Any]], EventType[Dict[str, str]]]
] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "FormRoot":
"""Create a form component.
Args:
*children: The children of the form.
+ on_clear_server_errors: Fired when the errors are cleared.
as_child: Change the default rendered element for the one passed as a child.
accept: MIME types the server accepts for file upload
accept_charset: Character encodings to be used for form submission
@@ -245,6 +152,7 @@ class FormRoot(FormComponent, HTMLForm):
target: Where to display the response after submitting the form
reset_on_submit: If true, the form will be cleared after submit.
handle_submit_unique_name: The name used to make this form's submit handler function unique.
+ on_submit: Fired when the form is submitted
access_key: Provides a hint for generating a keyboard shortcut for the current element.
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
content_editable: Indicates whether the element's content is editable.
@@ -275,7 +183,7 @@ class FormRoot(FormComponent, HTMLForm):
...
class FormField(FormComponent):
- def add_style(self) -> Style | None: ...
+ def add_style(self) -> dict[str, Any] | None: ...
@overload
@classmethod
def create( # type: ignore
@@ -290,52 +198,22 @@ class FormField(FormComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "FormField":
"""Create the component.
@@ -358,7 +236,7 @@ class FormField(FormComponent):
...
class FormLabel(FormComponent):
- def add_style(self) -> Style | None: ...
+ def add_style(self) -> dict[str, Any] | None: ...
@overload
@classmethod
def create( # type: ignore
@@ -371,52 +249,22 @@ class FormLabel(FormComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "FormLabel":
"""Create the component.
@@ -449,52 +297,22 @@ class FormControl(FormComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "FormControl":
"""Create a Form Control component.
@@ -532,7 +350,7 @@ LiteralMatcher = Literal[
]
class FormMessage(FormComponent):
- def add_style(self) -> Style | None: ...
+ def add_style(self) -> dict[str, Any] | None: ...
@overload
@classmethod
def create( # type: ignore
@@ -541,6 +359,18 @@ class FormMessage(FormComponent):
name: Optional[Union[Var[str], str]] = None,
match: Optional[
Union[
+ Literal[
+ "badInput",
+ "patternMismatch",
+ "rangeOverflow",
+ "rangeUnderflow",
+ "stepMismatch",
+ "tooLong",
+ "tooShort",
+ "typeMismatch",
+ "valid",
+ "valueMissing",
+ ],
Var[
Literal[
"badInput",
@@ -555,18 +385,6 @@ class FormMessage(FormComponent):
"valueMissing",
]
],
- Literal[
- "badInput",
- "patternMismatch",
- "rangeOverflow",
- "rangeUnderflow",
- "stepMismatch",
- "tooLong",
- "tooShort",
- "typeMismatch",
- "valid",
- "valueMissing",
- ],
]
] = None,
force_match: Optional[Union[Var[bool], bool]] = None,
@@ -577,52 +395,22 @@ class FormMessage(FormComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "FormMessage":
"""Create the component.
@@ -658,52 +446,22 @@ class FormValidityState(FormComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "FormValidityState":
"""Create the component.
@@ -736,52 +494,22 @@ class FormSubmit(FormComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "FormSubmit":
"""Create the component.
@@ -810,136 +538,77 @@ class Form(FormRoot):
cls,
*children,
as_child: Optional[Union[Var[bool], bool]] = None,
- accept: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ accept: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
accept_charset: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- action: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ action: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_complete: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- enc_type: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- method: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- name: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- no_validate: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- target: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ enc_type: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ method: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ name: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ no_validate: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ target: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
reset_on_submit: Optional[Union[Var[bool], bool]] = None,
handle_submit_unique_name: Optional[Union[Var[str], str]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_clear_server_errors: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_clear_server_errors: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
on_submit: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
+ Union[EventType[Dict[str, Any]], EventType[Dict[str, str]]]
] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Form":
"""Create a form component.
Args:
*children: The children of the form.
+ on_clear_server_errors: Fired when the errors are cleared.
as_child: Change the default rendered element for the one passed as a child.
accept: MIME types the server accepts for file upload
accept_charset: Character encodings to be used for form submission
@@ -952,6 +621,7 @@ class Form(FormRoot):
target: Where to display the response after submitting the form
reset_on_submit: If true, the form will be cleared after submit.
handle_submit_unique_name: The name used to make this form's submit handler function unique.
+ on_submit: Fired when the form is submitted
access_key: Provides a hint for generating a keyboard shortcut for the current element.
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
content_editable: Indicates whether the element's content is editable.
@@ -994,136 +664,77 @@ class FormNamespace(ComponentNamespace):
def __call__(
*children,
as_child: Optional[Union[Var[bool], bool]] = None,
- accept: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ accept: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
accept_charset: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- action: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ action: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_complete: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- enc_type: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- method: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- name: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- no_validate: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- target: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ enc_type: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ method: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ name: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ no_validate: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ target: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
reset_on_submit: Optional[Union[Var[bool], bool]] = None,
handle_submit_unique_name: Optional[Union[Var[str], str]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_clear_server_errors: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_clear_server_errors: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
on_submit: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
+ Union[EventType[Dict[str, Any]], EventType[Dict[str, str]]]
] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Form":
"""Create a form component.
Args:
*children: The children of the form.
+ on_clear_server_errors: Fired when the errors are cleared.
as_child: Change the default rendered element for the one passed as a child.
accept: MIME types the server accepts for file upload
accept_charset: Character encodings to be used for form submission
@@ -1136,6 +747,7 @@ class FormNamespace(ComponentNamespace):
target: Where to display the response after submitting the form
reset_on_submit: If true, the form will be cleared after submit.
handle_submit_unique_name: The name used to make this form's submit handler function unique.
+ on_submit: Fired when the form is submitted
access_key: Provides a hint for generating a keyboard shortcut for the current element.
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
content_editable: Indicates whether the element's content is editable.
diff --git a/reflex/components/radix/primitives/progress.py b/reflex/components/radix/primitives/progress.py
index 313d6aeb6..72aee1038 100644
--- a/reflex/components/radix/primitives/progress.py
+++ b/reflex/components/radix/primitives/progress.py
@@ -2,15 +2,14 @@
from __future__ import annotations
-from typing import Optional
+from typing import Any, Optional
from reflex.components.component import Component, ComponentNamespace
from reflex.components.core.colors import color
from reflex.components.radix.primitives.accordion import DEFAULT_ANIMATION_DURATION
from reflex.components.radix.primitives.base import RadixPrimitiveComponentWithClassName
from reflex.components.radix.themes.base import LiteralAccentColor, LiteralRadius
-from reflex.style import Style
-from reflex.vars import Var
+from reflex.vars.base import Var
class ProgressComponent(RadixPrimitiveComponentWithClassName):
@@ -28,7 +27,7 @@ class ProgressRoot(ProgressComponent):
# Override theme radius for progress bar: "none" | "small" | "medium" | "large" | "full"
radius: Var[LiteralRadius]
- def add_style(self) -> Style | None:
+ def add_style(self) -> dict[str, Any] | None:
"""Add style to the component.
Returns:
@@ -37,17 +36,15 @@ class ProgressRoot(ProgressComponent):
if self.radius is not None:
self.custom_attrs["data-radius"] = self.radius
- return Style(
- {
- "position": "relative",
- "overflow": "hidden",
- "background": color("gray", 3, alpha=True),
- "border_radius": "max(var(--radius-2), var(--radius-full))",
- "width": "100%",
- "height": "20px",
- "boxShadow": f"inset 0 0 0 1px {color('gray', 5, alpha=True)}",
- }
- )
+ return {
+ "position": "relative",
+ "overflow": "hidden",
+ "background": color("gray", 3, alpha=True),
+ "border_radius": "max(var(--radius-2), var(--radius-full))",
+ "width": "100%",
+ "height": "20px",
+ "boxShadow": f"inset 0 0 0 1px {color('gray', 5, alpha=True)}",
+ }
def _exclude_props(self) -> list[str]:
return ["radius"]
@@ -69,7 +66,7 @@ class ProgressIndicator(ProgressComponent):
# The color scheme of the progress indicator.
color_scheme: Var[LiteralAccentColor]
- def add_style(self) -> Style | None:
+ def add_style(self) -> dict[str, Any] | None:
"""Add style to the component.
Returns:
@@ -78,19 +75,17 @@ class ProgressIndicator(ProgressComponent):
if self.color_scheme is not None:
self.custom_attrs["data-accent-color"] = self.color_scheme
- return Style(
- {
- "background_color": color("accent", 9),
- "width": "100%",
- "height": "100%",
+ return {
+ "background_color": color("accent", 9),
+ "width": "100%",
+ "height": "100%",
+ "transition": f"transform {DEFAULT_ANIMATION_DURATION}ms linear",
+ "&[data_state='loading']": {
"transition": f"transform {DEFAULT_ANIMATION_DURATION}ms linear",
- "&[data_state='loading']": {
- "transition": f"transform {DEFAULT_ANIMATION_DURATION}ms linear",
- },
- "transform": f"translateX(calc(-100% + ({self.value} / {self.max} * 100%)))", # type: ignore
- "boxShadow": "inset 0 0 0 1px var(--gray-a5)",
- }
- )
+ },
+ "transform": f"translateX(calc(-100% + ({self.value} / {self.max} * 100%)))", # type: ignore
+ "boxShadow": "inset 0 0 0 1px var(--gray-a5)",
+ }
def _exclude_props(self) -> list[str]:
return ["color_scheme"]
diff --git a/reflex/components/radix/primitives/progress.pyi b/reflex/components/radix/primitives/progress.pyi
index eb0149496..c760c0a57 100644
--- a/reflex/components/radix/primitives/progress.pyi
+++ b/reflex/components/radix/primitives/progress.pyi
@@ -1,20 +1,15 @@
"""Stub file for reflex/components/radix/primitives/progress.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Optional
-from reflex.components.component import Component, ComponentNamespace
-from reflex.components.core.colors import color
-from reflex.components.radix.primitives.accordion import DEFAULT_ANIMATION_DURATION
+
+from reflex.components.component import ComponentNamespace
from reflex.components.radix.primitives.base import RadixPrimitiveComponentWithClassName
-from reflex.components.radix.themes.base import LiteralAccentColor, LiteralRadius
+from reflex.event import EventType
from reflex.style import Style
-from reflex.vars import Var
+from reflex.vars.base import Var
class ProgressComponent(RadixPrimitiveComponentWithClassName):
@overload
@@ -29,52 +24,22 @@ class ProgressComponent(RadixPrimitiveComponentWithClassName):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ProgressComponent":
"""Create the component.
@@ -95,7 +60,7 @@ class ProgressComponent(RadixPrimitiveComponentWithClassName):
...
class ProgressRoot(ProgressComponent):
- def add_style(self) -> Style | None: ...
+ def add_style(self) -> dict[str, Any] | None: ...
@overload
@classmethod
def create( # type: ignore
@@ -103,8 +68,8 @@ class ProgressRoot(ProgressComponent):
*children,
radius: Optional[
Union[
- Var[Literal["none", "small", "medium", "large", "full"]],
- Literal["none", "small", "medium", "large", "full"],
+ Literal["full", "large", "medium", "none", "small"],
+ Var[Literal["full", "large", "medium", "none", "small"]],
]
] = None,
as_child: Optional[Union[Var[bool], bool]] = None,
@@ -114,52 +79,22 @@ class ProgressRoot(ProgressComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ProgressRoot":
"""Create the component.
@@ -181,73 +116,73 @@ class ProgressRoot(ProgressComponent):
...
class ProgressIndicator(ProgressComponent):
- def add_style(self) -> Style | None: ...
+ def add_style(self) -> dict[str, Any] | None: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- value: Optional[Union[Var[Optional[int]], Optional[int]]] = None,
- max: Optional[Union[Var[Optional[int]], Optional[int]]] = None,
+ value: Optional[Union[Var[Optional[int]], int]] = None,
+ max: Optional[Union[Var[Optional[int]], int]] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
@@ -258,52 +193,22 @@ class ProgressIndicator(ProgressComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ProgressIndicator":
"""Create the component.
@@ -334,72 +239,72 @@ class Progress(ProgressRoot):
*children,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
- value: Optional[Union[Var[Optional[int]], Optional[int]]] = None,
- max: Optional[Union[Var[Optional[int]], Optional[int]]] = None,
+ value: Optional[Union[Var[Optional[int]], int]] = None,
+ max: Optional[Union[Var[Optional[int]], int]] = None,
radius: Optional[
Union[
- Var[Literal["none", "small", "medium", "large", "full"]],
- Literal["none", "small", "medium", "large", "full"],
+ Literal["full", "large", "medium", "none", "small"],
+ Var[Literal["full", "large", "medium", "none", "small"]],
]
] = None,
as_child: Optional[Union[Var[bool], bool]] = None,
@@ -409,52 +314,22 @@ class Progress(ProgressRoot):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Progress":
"""High-level API for progress bar.
@@ -486,72 +361,72 @@ class ProgressNamespace(ComponentNamespace):
*children,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
- value: Optional[Union[Var[Optional[int]], Optional[int]]] = None,
- max: Optional[Union[Var[Optional[int]], Optional[int]]] = None,
+ value: Optional[Union[Var[Optional[int]], int]] = None,
+ max: Optional[Union[Var[Optional[int]], int]] = None,
radius: Optional[
Union[
- Var[Literal["none", "small", "medium", "large", "full"]],
- Literal["none", "small", "medium", "large", "full"],
+ Literal["full", "large", "medium", "none", "small"],
+ Var[Literal["full", "large", "medium", "none", "small"]],
]
] = None,
as_child: Optional[Union[Var[bool], bool]] = None,
@@ -561,52 +436,22 @@ class ProgressNamespace(ComponentNamespace):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Progress":
"""High-level API for progress bar.
diff --git a/reflex/components/radix/primitives/slider.py b/reflex/components/radix/primitives/slider.py
index 2e0b1ef49..10a0079a4 100644
--- a/reflex/components/radix/primitives/slider.py
+++ b/reflex/components/radix/primitives/slider.py
@@ -2,12 +2,12 @@
from __future__ import annotations
-from typing import Any, Dict, List, Literal
+from typing import Any, List, Literal, Tuple
from reflex.components.component import Component, ComponentNamespace
from reflex.components.radix.primitives.base import RadixPrimitiveComponentWithClassName
-from reflex.style import Style
-from reflex.vars import Var
+from reflex.event import EventHandler
+from reflex.vars.base import Var
LiteralSliderOrientation = Literal["horizontal", "vertical"]
LiteralSliderDir = Literal["ltr", "rtl"]
@@ -19,6 +19,20 @@ class SliderComponent(RadixPrimitiveComponentWithClassName):
library = "@radix-ui/react-slider@^1.1.2"
+def on_value_event_spec(
+ value: Var[List[int]],
+) -> Tuple[Var[List[int]]]:
+ """Event handler spec for the value event.
+
+ Args:
+ value: The value of the event.
+
+ Returns:
+ The event handler spec.
+ """
+ return (value,) # type: ignore
+
+
class SliderRoot(SliderComponent):
"""The Slider component comtaining all slider parts."""
@@ -47,40 +61,32 @@ class SliderRoot(SliderComponent):
min_steps_between_thumbs: Var[int]
- def get_event_triggers(self) -> Dict[str, Any]:
- """Event triggers for radix slider primitive.
+ # Fired when the value of a thumb changes.
+ on_value_change: EventHandler[on_value_event_spec]
- Returns:
- The triggers for event supported by radix primitives.
- """
- return {
- **super().get_event_triggers(),
- "on_value_change": lambda e0: [e0], # trigger for all change of a thumb
- "on_value_commit": lambda e0: [e0], # trigger when thumb is released
- }
+ # Fired when a thumb is released.
+ on_value_commit: EventHandler[on_value_event_spec]
- def add_style(self) -> Style | None:
+ def add_style(self) -> dict[str, Any] | None:
"""Add style to the component.
Returns:
The style of the component.
"""
- return Style(
- {
- "position": "relative",
- "display": "flex",
- "align_items": "center",
- "user_select": "none",
- "touch_action": "none",
- "width": "200px",
- "height": "20px",
- "&[data-orientation='vertical']": {
- "flex_direction": "column",
- "width": "20px",
- "height": "100px",
- },
- }
- )
+ return {
+ "position": "relative",
+ "display": "flex",
+ "align_items": "center",
+ "user_select": "none",
+ "touch_action": "none",
+ "width": "200px",
+ "height": "20px",
+ "&[data-orientation='vertical']": {
+ "flex_direction": "column",
+ "width": "20px",
+ "height": "100px",
+ },
+ }
class SliderTrack(SliderComponent):
@@ -89,22 +95,20 @@ class SliderTrack(SliderComponent):
tag = "Track"
alias = "RadixSliderTrack"
- def add_style(self) -> Style | None:
+ def add_style(self) -> dict[str, Any] | None:
"""Add style to the component.
Returns:
The style of the component.
"""
- return Style(
- {
- "position": "relative",
- "flex_grow": "1",
- "background_color": "black",
- "border_radius": "9999px",
- "height": "3px",
- "&[data-orientation='vertical']": {"width": "3px"},
- }
- )
+ return {
+ "position": "relative",
+ "flex_grow": "1",
+ "background_color": "black",
+ "border_radius": "9999px",
+ "height": "3px",
+ "&[data-orientation='vertical']": {"width": "3px"},
+ }
class SliderRange(SliderComponent):
@@ -113,20 +117,18 @@ class SliderRange(SliderComponent):
tag = "Range"
alias = "RadixSliderRange"
- def add_style(self) -> Style | None:
+ def add_style(self) -> dict[str, Any] | None:
"""Add style to the component.
Returns:
The style of the component.
"""
- return Style(
- {
- "position": "absolute",
- "background_color": "white",
- "height": "100%",
- "&[data-orientation='vertical']": {"width": "100%"},
- }
- )
+ return {
+ "position": "absolute",
+ "background_color": "white",
+ "height": "100%",
+ "&[data-orientation='vertical']": {"width": "100%"},
+ }
class SliderThumb(SliderComponent):
@@ -135,29 +137,27 @@ class SliderThumb(SliderComponent):
tag = "Thumb"
alias = "RadixSliderThumb"
- def add_style(self) -> Style | None:
+ def add_style(self) -> dict[str, Any] | None:
"""Add style to the component.
Returns:
The style of the component.
"""
- return Style(
- {
- "display": "block",
- "width": "20px",
- "height": "20px",
- "background_color": "black",
- "box_shadow": "0 2px 10px black",
- "border_radius": "10px",
- "&:hover": {
- "background_color": "gray",
- },
- "&:focus": {
- "outline": "none",
- "box_shadow": "0 0 0 4px gray",
- },
- }
- )
+ return {
+ "display": "block",
+ "width": "20px",
+ "height": "20px",
+ "background_color": "black",
+ "box_shadow": "0 2px 10px black",
+ "border_radius": "10px",
+ "&:hover": {
+ "background_color": "gray",
+ },
+ "&:focus": {
+ "outline": "none",
+ "box_shadow": "0 0 0 4px gray",
+ },
+ }
class Slider(ComponentNamespace):
diff --git a/reflex/components/radix/primitives/slider.pyi b/reflex/components/radix/primitives/slider.pyi
index 1f837d732..03a30f164 100644
--- a/reflex/components/radix/primitives/slider.pyi
+++ b/reflex/components/radix/primitives/slider.pyi
@@ -1,17 +1,15 @@
"""Stub file for reflex/components/radix/primitives/slider.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, List, Literal, Optional, Tuple, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Any, Dict, List, Literal
from reflex.components.component import Component, ComponentNamespace
from reflex.components.radix.primitives.base import RadixPrimitiveComponentWithClassName
+from reflex.event import EventType
from reflex.style import Style
-from reflex.vars import Var
+from reflex.vars.base import Var
LiteralSliderOrientation = Literal["horizontal", "vertical"]
LiteralSliderDir = Literal["ltr", "rtl"]
@@ -29,52 +27,22 @@ class SliderComponent(RadixPrimitiveComponentWithClassName):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "SliderComponent":
"""Create the component.
@@ -94,25 +62,26 @@ class SliderComponent(RadixPrimitiveComponentWithClassName):
"""
...
+def on_value_event_spec(value: Var[List[int]]) -> Tuple[Var[List[int]]]: ...
+
class SliderRoot(SliderComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
- def add_style(self) -> Style | None: ...
+ def add_style(self) -> dict[str, Any] | None: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- default_value: Optional[Union[Var[List[int]], List[int]]] = None,
- value: Optional[Union[Var[List[int]], List[int]]] = None,
+ default_value: Optional[Union[List[int], Var[List[int]]]] = None,
+ value: Optional[Union[List[int], Var[List[int]]]] = None,
name: Optional[Union[Var[str], str]] = None,
disabled: Optional[Union[Var[bool], bool]] = None,
orientation: Optional[
Union[
- Var[Literal["horizontal", "vertical"]],
Literal["horizontal", "vertical"],
+ Var[Literal["horizontal", "vertical"]],
]
] = None,
- dir: Optional[Union[Var[Literal["ltr", "rtl"]], Literal["ltr", "rtl"]]] = None,
+ dir: Optional[Union[Literal["ltr", "rtl"], Var[Literal["ltr", "rtl"]]]] = None,
inverted: Optional[Union[Var[bool], bool]] = None,
min: Optional[Union[Var[int], int]] = None,
max: Optional[Union[Var[int], int]] = None,
@@ -125,63 +94,31 @@ class SliderRoot(SliderComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_value_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_value_commit: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ on_value_change: Optional[EventType[List[int]]] = None,
+ on_value_commit: Optional[EventType[List[int]]] = None,
+ **props,
) -> "SliderRoot":
"""Create the component.
Args:
*children: The children of the component.
+ on_value_change: Fired when the value of a thumb changes.
+ on_value_commit: Fired when a thumb is released.
as_child: Change the default rendered element for the one passed as a child.
style: The style of the component.
key: A unique key for the component.
@@ -197,7 +134,7 @@ class SliderRoot(SliderComponent):
...
class SliderTrack(SliderComponent):
- def add_style(self) -> Style | None: ...
+ def add_style(self) -> dict[str, Any] | None: ...
@overload
@classmethod
def create( # type: ignore
@@ -210,52 +147,22 @@ class SliderTrack(SliderComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "SliderTrack":
"""Create the component.
@@ -276,7 +183,7 @@ class SliderTrack(SliderComponent):
...
class SliderRange(SliderComponent):
- def add_style(self) -> Style | None: ...
+ def add_style(self) -> dict[str, Any] | None: ...
@overload
@classmethod
def create( # type: ignore
@@ -289,52 +196,22 @@ class SliderRange(SliderComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "SliderRange":
"""Create the component.
@@ -355,7 +232,7 @@ class SliderRange(SliderComponent):
...
class SliderThumb(SliderComponent):
- def add_style(self) -> Style | None: ...
+ def add_style(self) -> dict[str, Any] | None: ...
@overload
@classmethod
def create( # type: ignore
@@ -368,52 +245,22 @@ class SliderThumb(SliderComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "SliderThumb":
"""Create the component.
diff --git a/reflex/components/radix/themes/__init__.py b/reflex/components/radix/themes/__init__.py
index e1d39fb52..0afd5aa5d 100644
--- a/reflex/components/radix/themes/__init__.py
+++ b/reflex/components/radix/themes/__init__.py
@@ -1,7 +1,22 @@
"""Namespace for components provided by the @radix-ui/themes library."""
-from .base import theme as theme
-from .base import theme_panel as theme_panel
-from .color_mode import color_mode_var_and_namespace as color_mode
-from .components import *
-from .layout import *
-from .typography import *
+
+from __future__ import annotations
+
+from reflex.utils import lazy_loader
+
+_SUBMODULES: set[str] = {"components", "layout", "typography"}
+_SUBMOD_ATTRS: dict[str, list[str]] = {
+ "base": [
+ "theme",
+ "theme_panel",
+ ],
+ "color_mode": [
+ "color_mode",
+ ],
+}
+
+__getattr__, __dir__, __all__ = lazy_loader.attach(
+ __name__,
+ submodules=_SUBMODULES,
+ submod_attrs=_SUBMOD_ATTRS,
+)
diff --git a/reflex/components/radix/themes/__init__.pyi b/reflex/components/radix/themes/__init__.pyi
new file mode 100644
index 000000000..91ef2b46c
--- /dev/null
+++ b/reflex/components/radix/themes/__init__.pyi
@@ -0,0 +1,11 @@
+"""Stub file for reflex/components/radix/themes/__init__.py"""
+# ------------------- DO NOT EDIT ----------------------
+# This file was generated by `reflex/utils/pyi_generator.py`!
+# ------------------------------------------------------
+
+from . import components as components
+from . import layout as layout
+from . import typography as typography
+from .base import theme as theme
+from .base import theme_panel as theme_panel
+from .color_mode import color_mode as color_mode
diff --git a/reflex/components/radix/themes/base.py b/reflex/components/radix/themes/base.py
index 559d10239..acca1dce8 100644
--- a/reflex/components/radix/themes/base.py
+++ b/reflex/components/radix/themes/base.py
@@ -6,8 +6,9 @@ from typing import Any, Dict, Literal
from reflex.components import Component
from reflex.components.tags import Tag
-from reflex.utils import imports
-from reflex.vars import Var
+from reflex.config import get_config
+from reflex.utils.imports import ImportDict, ImportVar
+from reflex.vars.base import Var
LiteralAlign = Literal["start", "center", "end", "baseline", "stretch"]
LiteralJustify = Literal["start", "center", "end", "between"]
@@ -112,6 +113,11 @@ class RadixThemesComponent(Component):
component.alias = "RadixThemes" + (
component.tag or component.__class__.__name__
)
+ # value = props.get("value")
+ # if value is not None and component.alias == "RadixThemesSelect.Root":
+ # lv = LiteralVar.create(value)
+ # print(repr(lv))
+ # print(f"Warning: Value {value} is not used in {component.alias}.")
return component
@staticmethod
@@ -208,25 +214,29 @@ class Theme(RadixThemesComponent):
children = [ThemePanel.create(), *children]
return super().create(*children, **props)
- def _get_imports(self) -> imports.ImportDict:
- return imports.merge_imports(
- super()._get_imports(),
- {
- "": [
- imports.ImportVar(tag="@radix-ui/themes/styles.css", install=False)
- ],
- "/utils/theme.js": [
- imports.ImportVar(tag="theme", is_default=True),
- ],
- },
- )
+ def add_imports(self) -> ImportDict | list[ImportDict]:
+ """Add imports for the Theme component.
+
+ Returns:
+ The import dict.
+ """
+ _imports: ImportDict = {
+ "$/utils/theme.js": [ImportVar(tag="theme", is_default=True)],
+ }
+ if get_config().tailwind is None:
+ # When tailwind is disabled, import the radix-ui styles directly because they will
+ # not be included in the tailwind.css file.
+ _imports[""] = ImportVar(
+ tag="@radix-ui/themes/styles.css",
+ install=False,
+ )
+ return _imports
def _render(self, props: dict[str, Any] | None = None) -> Tag:
tag = super()._render(props)
tag.add_props(
- css=Var.create(
- "{{...theme.styles.global[':root'], ...theme.styles.global.body}}",
- _var_is_local=False,
+ css=Var(
+ _js_expr=f"{{...theme.styles.global[':root'], ...theme.styles.global.body}}"
),
)
return tag
@@ -243,32 +253,19 @@ class ThemePanel(RadixThemesComponent):
# Whether the panel is open. Defaults to False.
default_open: Var[bool]
- def _get_imports(self) -> dict[str, list[imports.ImportVar]]:
- return imports.merge_imports(
- super()._get_imports(),
- {
- "react": [imports.ImportVar(tag="useEffect")],
- },
- )
+ def add_imports(self) -> dict[str, str]:
+ """Add imports for the ThemePanel component.
- def _get_hooks(self) -> str | None:
- # The panel freezes the tab if the user color preference differs from the
- # theme "appearance", so clear it out when theme panel is used.
- return """
- useEffect(() => {
- if (typeof window !== 'undefined') {
- window.onbeforeunload = () => {
- localStorage.removeItem('chakra-ui-color-mode');
- }
- window.onbeforeunload();
- }
- }, [])"""
+ Returns:
+ The import dict.
+ """
+ return {"react": "useEffect"}
class RadixThemesColorModeProvider(Component):
"""Next-themes integration for radix themes components."""
- library = "/components/reflex/radix_themes_color_mode_provider.js"
+ library = "$/components/reflex/radix_themes_color_mode_provider.js"
tag = "RadixThemesColorModeProvider"
is_default = True
diff --git a/reflex/components/radix/themes/base.pyi b/reflex/components/radix/themes/base.pyi
index d7ee29801..0f0de5401 100644
--- a/reflex/components/radix/themes/base.pyi
+++ b/reflex/components/radix/themes/base.pyi
@@ -1,17 +1,15 @@
"""Stub file for reflex/components/radix/themes/base.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Any, Dict, Literal
+
from reflex.components import Component
-from reflex.components.tags import Tag
-from reflex.utils import imports
-from reflex.vars import Var
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.utils.imports import ImportDict
+from reflex.vars.base import Var
LiteralAlign = Literal["start", "center", "end", "baseline", "stretch"]
LiteralJustify = Literal["start", "center", "end", "between"]
@@ -59,44 +57,44 @@ class CommonMarginProps(Component):
*children,
m: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
]
] = None,
mx: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
]
] = None,
my: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
]
] = None,
mt: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
]
] = None,
mr: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
]
] = None,
mb: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
]
] = None,
ml: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
]
] = None,
style: Optional[Style] = None,
@@ -105,52 +103,22 @@ class CommonMarginProps(Component):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "CommonMarginProps":
"""Create the component.
@@ -189,52 +157,22 @@ class RadixLoadingProp(Component):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "RadixLoadingProp":
"""Create the component.
@@ -266,52 +204,22 @@ class RadixThemesComponent(Component):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "RadixThemesComponent":
"""Create a new component instance.
@@ -345,52 +253,22 @@ class RadixThemesTriggerComponent(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "RadixThemesTriggerComponent":
"""Create a new RadixThemesTriggerComponent instance.
@@ -409,96 +287,96 @@ class Theme(RadixThemesComponent):
def create( # type: ignore
cls,
*children,
- color_mode: Optional[Literal["inherit", "light", "dark"]] = None,
+ color_mode: Optional[Literal["dark", "inherit", "light"]] = None,
theme_panel: Optional[bool] = False,
has_background: Optional[Union[Var[bool], bool]] = None,
appearance: Optional[
Union[
- Var[Literal["inherit", "light", "dark"]],
- Literal["inherit", "light", "dark"],
+ Literal["dark", "inherit", "light"],
+ Var[Literal["dark", "inherit", "light"]],
]
] = None,
accent_color: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
gray_color: Optional[
Union[
- Var[Literal["gray", "mauve", "slate", "sage", "olive", "sand", "auto"]],
- Literal["gray", "mauve", "slate", "sage", "olive", "sand", "auto"],
+ Literal["auto", "gray", "mauve", "olive", "sage", "sand", "slate"],
+ Var[Literal["auto", "gray", "mauve", "olive", "sage", "sand", "slate"]],
]
] = None,
panel_background: Optional[
- Union[Var[Literal["solid", "translucent"]], Literal["solid", "translucent"]]
+ Union[Literal["solid", "translucent"], Var[Literal["solid", "translucent"]]]
] = None,
radius: Optional[
Union[
- Var[Literal["none", "small", "medium", "large", "full"]],
- Literal["none", "small", "medium", "large", "full"],
+ Literal["full", "large", "medium", "none", "small"],
+ Var[Literal["full", "large", "medium", "none", "small"]],
]
] = None,
scaling: Optional[
Union[
- Var[Literal["90%", "95%", "100%", "105%", "110%"]],
- Literal["90%", "95%", "100%", "105%", "110%"],
+ Literal["100%", "105%", "110%", "90%", "95%"],
+ Var[Literal["100%", "105%", "110%", "90%", "95%"]],
]
] = None,
style: Optional[Style] = None,
@@ -507,52 +385,22 @@ class Theme(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Theme":
"""Create a new Radix Theme specification.
@@ -580,7 +428,10 @@ class Theme(RadixThemesComponent):
"""
...
+ def add_imports(self) -> ImportDict | list[ImportDict]: ...
+
class ThemePanel(RadixThemesComponent):
+ def add_imports(self) -> dict[str, str]: ...
@overload
@classmethod
def create( # type: ignore
@@ -593,52 +444,22 @@ class ThemePanel(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ThemePanel":
"""Create a new component instance.
@@ -673,52 +494,22 @@ class RadixThemesColorModeProvider(Component):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "RadixThemesColorModeProvider":
"""Create the component.
diff --git a/reflex/components/radix/themes/color_mode.py b/reflex/components/radix/themes/color_mode.py
index 2329918f4..a01d40e07 100644
--- a/reflex/components/radix/themes/color_mode.py
+++ b/reflex/components/radix/themes/color_mode.py
@@ -17,16 +17,22 @@ rx.text(
from __future__ import annotations
-import dataclasses
-from typing import Literal, get_args
+from typing import Dict, List, Literal, Optional, Union, get_args
from reflex.components.component import BaseComponent
from reflex.components.core.cond import Cond, color_mode_cond, cond
from reflex.components.lucide.icon import Icon
+from reflex.components.radix.themes.components.dropdown_menu import dropdown_menu
from reflex.components.radix.themes.components.switch import Switch
-from reflex.style import LIGHT_COLOR_MODE, color_mode, toggle_color_mode
-from reflex.utils import console
-from reflex.vars import BaseVar, Var
+from reflex.style import (
+ LIGHT_COLOR_MODE,
+ color_mode,
+ resolved_color_mode,
+ set_color_mode,
+ toggle_color_mode,
+)
+from reflex.vars.base import Var
+from reflex.vars.sequence import LiteralArrayVar
from .components.icon_button import IconButton
@@ -60,9 +66,9 @@ class ColorModeIcon(Cond):
LiteralPosition = Literal["top-left", "top-right", "bottom-left", "bottom-right"]
-position_values = get_args(LiteralPosition)
+position_values: List[str] = list(get_args(LiteralPosition))
-position_map = {
+position_map: Dict[str, List[str]] = {
"position": position_values,
"left": ["top-left", "bottom-left"],
"right": ["top-right", "bottom-right"],
@@ -72,8 +78,8 @@ position_map = {
# needed to inverse contains for find
-def _find(const, var):
- return Var.create_safe(const).contains(var)
+def _find(const: List[str], var):
+ return LiteralArrayVar.create(const).contains(var)
def _set_var_default(props, position, prop, default1, default2=""):
@@ -90,34 +96,31 @@ def _set_static_default(props, position, prop, default):
class ColorModeIconButton(IconButton):
"""Icon Button for toggling light / dark mode via toggle_color_mode."""
+ # The position of the icon button. Follow document flow if None.
+ position: Optional[Union[LiteralPosition, Var[LiteralPosition]]] = None
+
+ # Allow picking the "system" value for the color mode.
+ allow_system: bool = False
+
@classmethod
def create(
cls,
- *children,
- position: LiteralPosition | None = None,
**props,
):
- """Create a icon button component that calls toggle_color_mode on click.
+ """Create an icon button component that calls toggle_color_mode on click.
Args:
- *children: The children of the component.
- position: The position of the icon button. Follow document flow if None.
**props: The props to pass to the component.
Returns:
The button component.
"""
- if children:
- console.deprecate(
- feature_name="passing children to color_mode.button",
- reason=", use color_mode_cond and toggle_color_mode instead to build a custom color_mode component",
- deprecation_version="0.5.0",
- removal_version="0.6.0",
- )
+ position = props.pop("position", None)
+ allow_system = props.pop("allow_system", False)
# position is used to set nice defaults for positioning the icon button
if isinstance(position, Var):
- _set_var_default(props, position, "position", "fixed", position)
+ _set_var_default(props, position, "position", "fixed", position) # type: ignore
_set_var_default(props, position, "bottom", "2rem")
_set_var_default(props, position, "top", "2rem")
_set_var_default(props, position, "left", "2rem")
@@ -137,12 +140,35 @@ class ColorModeIconButton(IconButton):
props.setdefault("z_index", "20")
props.setdefault(":hover", {"cursor": "pointer"})
- return super().create(
+ if allow_system:
+
+ def color_mode_item(_color_mode):
+ return dropdown_menu.item(
+ _color_mode.title(), on_click=set_color_mode(_color_mode)
+ )
+
+ return dropdown_menu.root(
+ dropdown_menu.trigger(
+ super().create(
+ ColorModeIcon.create(),
+ **props,
+ )
+ ),
+ dropdown_menu.content(
+ color_mode_item("light"),
+ color_mode_item("dark"),
+ color_mode_item("system"),
+ ),
+ )
+ return IconButton.create(
ColorModeIcon.create(),
on_click=toggle_color_mode,
**props,
)
+ def _exclude_props(self) -> list[str]:
+ return ["position", "allow_system"]
+
class ColorModeSwitch(Switch):
"""Switch for toggling light / dark mode via toggle_color_mode."""
@@ -160,13 +186,13 @@ class ColorModeSwitch(Switch):
"""
return Switch.create(
*children,
- checked=color_mode != LIGHT_COLOR_MODE,
+ checked=resolved_color_mode != LIGHT_COLOR_MODE,
on_change=toggle_color_mode,
**props,
)
-class ColorModeNamespace(BaseVar):
+class ColorModeNamespace(Var):
"""Namespace for color mode components."""
icon = staticmethod(ColorModeIcon.create)
@@ -174,4 +200,8 @@ class ColorModeNamespace(BaseVar):
switch = staticmethod(ColorModeSwitch.create)
-color_mode_var_and_namespace = ColorModeNamespace(**dataclasses.asdict(color_mode))
+color_mode = color_mode_var_and_namespace = ColorModeNamespace(
+ _js_expr=color_mode._js_expr,
+ _var_type=color_mode._var_type,
+ _var_data=color_mode.get_default_value(),
+)
diff --git a/reflex/components/radix/themes/color_mode.pyi b/reflex/components/radix/themes/color_mode.pyi
index e4a2cbcac..a5b7b31ec 100644
--- a/reflex/components/radix/themes/color_mode.pyi
+++ b/reflex/components/radix/themes/color_mode.pyi
@@ -1,21 +1,22 @@
"""Stub file for reflex/components/radix/themes/color_mode.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, List, Literal, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-import dataclasses
-from typing import Literal, get_args
from reflex.components.component import BaseComponent
-from reflex.components.core.cond import Cond, color_mode_cond, cond
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.components.core.cond import Cond
from reflex.components.lucide.icon import Icon
from reflex.components.radix.themes.components.switch import Switch
-from reflex.style import LIGHT_COLOR_MODE, color_mode, toggle_color_mode
-from reflex.utils import console
-from reflex.vars import BaseVar, Var
+from reflex.event import EventType
+from reflex.style import (
+ Style,
+ color_mode,
+)
+from reflex.vars.base import Var
+
from .components.icon_button import IconButton
DEFAULT_LIGHT_ICON: Icon
@@ -27,7 +28,7 @@ class ColorModeIcon(Cond):
def create( # type: ignore
cls,
*children,
- cond: Optional[Union[Var[Any], Any]] = None,
+ cond: Optional[Union[Any, Var[Any]]] = None,
comp1: Optional[BaseComponent] = None,
comp2: Optional[BaseComponent] = None,
style: Optional[Style] = None,
@@ -36,52 +37,22 @@ class ColorModeIcon(Cond):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ColorModeIcon":
"""Create an icon component based on color_mode.
@@ -95,14 +66,8 @@ class ColorModeIcon(Cond):
...
LiteralPosition = Literal["top-left", "top-right", "bottom-left", "bottom-right"]
-position_values = get_args(LiteralPosition)
-position_map = {
- "position": position_values,
- "left": ["top-left", "bottom-left"],
- "right": ["top-right", "bottom-right"],
- "top": ["top-left", "top-right"],
- "bottom": ["bottom-left", "bottom-right"],
-}
+position_values: List[str]
+position_map: Dict[str, List[str]]
class ColorModeIconButton(IconButton):
@overload
@@ -111,152 +76,144 @@ class ColorModeIconButton(IconButton):
cls,
*children,
position: Optional[
- Literal["top-left", "top-right", "bottom-left", "bottom-right"]
+ Union[
+ Literal["bottom-left", "bottom-right", "top-left", "top-right"],
+ Union[
+ Literal["bottom-left", "bottom-right", "top-left", "top-right"],
+ Var[
+ Literal["bottom-left", "bottom-right", "top-left", "top-right"]
+ ],
+ ],
+ ]
] = None,
+ allow_system: Optional[bool] = None,
as_child: Optional[Union[Var[bool], bool]] = None,
size: Optional[
- Union[Var[Literal["1", "2", "3", "4"]], Literal["1", "2", "3", "4"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3", "4"]],
+ Literal["1", "2", "3", "4"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3", "4"]],
+ Literal["1", "2", "3", "4"],
+ ]
+ ],
+ ]
] = None,
variant: Optional[
Union[
- Var[Literal["classic", "solid", "soft", "surface", "outline", "ghost"]],
- Literal["classic", "solid", "soft", "surface", "outline", "ghost"],
+ Literal["classic", "ghost", "outline", "soft", "solid", "surface"],
+ Var[Literal["classic", "ghost", "outline", "soft", "solid", "surface"]],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
radius: Optional[
Union[
- Var[Literal["none", "small", "medium", "large", "full"]],
- Literal["none", "small", "medium", "large", "full"],
+ Literal["full", "large", "medium", "none", "small"],
+ Var[Literal["full", "large", "medium", "none", "small"]],
]
] = None,
- auto_focus: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ auto_focus: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
disabled: Optional[Union[Var[bool], bool]] = None,
- form: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- form_action: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ form: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ form_action: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
form_enc_type: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- form_method: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ form_method: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
form_no_validate: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- form_target: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- name: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- type: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- value: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ form_target: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ name: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ type: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ value: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
loading: Optional[Union[Var[bool], bool]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
@@ -264,58 +221,28 @@ class ColorModeIconButton(IconButton):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ColorModeIconButton":
- """Create a icon button component that calls toggle_color_mode on click.
+ """Create an icon button component that calls toggle_color_mode on click.
Args:
- *children: The children of the component.
position: The position of the icon button. Follow document flow if None.
+ allow_system: Allow picking the "system" value for the color mode.
as_child: Change the default rendered element for the one passed as a child, merging their props and behavior.
size: Button size "1" - "4"
variant: Variant of button: "classic" | "solid" | "soft" | "surface" | "outline" | "ghost"
@@ -377,80 +304,88 @@ class ColorModeSwitch(Switch):
name: Optional[Union[Var[str], str]] = None,
value: Optional[Union[Var[str], str]] = None,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
variant: Optional[
Union[
- Var[Literal["classic", "surface", "soft"]],
- Literal["classic", "surface", "soft"],
+ Literal["classic", "soft", "surface"],
+ Var[Literal["classic", "soft", "surface"]],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
radius: Optional[
Union[
- Var[Literal["none", "small", "full"]], Literal["none", "small", "full"]
+ Literal["full", "none", "small"], Var[Literal["full", "none", "small"]]
]
] = None,
style: Optional[Style] = None,
@@ -459,55 +394,23 @@ class ColorModeSwitch(Switch):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_change: Optional[EventType[bool]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ColorModeSwitch":
"""Create a switch component bound to color_mode.
@@ -525,6 +428,7 @@ class ColorModeSwitch(Switch):
color_scheme: Override theme color for switch
high_contrast: Whether to render the switch with higher contrast color against background
radius: Override theme radius for switch: "none" | "small" | "full"
+ on_change: Props to rename Fired when the value of the switch changes
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -538,9 +442,13 @@ class ColorModeSwitch(Switch):
"""
...
-class ColorModeNamespace(BaseVar):
+class ColorModeNamespace(Var):
icon = staticmethod(ColorModeIcon.create)
button = staticmethod(ColorModeIconButton.create)
switch = staticmethod(ColorModeSwitch.create)
-color_mode_var_and_namespace = ColorModeNamespace(**dataclasses.asdict(color_mode))
+color_mode = color_mode_var_and_namespace = ColorModeNamespace(
+ _js_expr=color_mode._js_expr,
+ _var_type=color_mode._var_type,
+ _var_data=color_mode.get_default_value(),
+)
diff --git a/reflex/components/radix/themes/components/__init__.py b/reflex/components/radix/themes/components/__init__.py
index 7df1f7707..ffb7a5806 100644
--- a/reflex/components/radix/themes/components/__init__.py
+++ b/reflex/components/radix/themes/components/__init__.py
@@ -1,83 +1,16 @@
"""Radix themes components."""
-from .alert_dialog import alert_dialog as alert_dialog
-from .aspect_ratio import aspect_ratio as aspect_ratio
-from .avatar import avatar as avatar
-from .badge import badge as badge
-from .button import button as button
-from .callout import callout as callout
-from .card import card as card
-from .checkbox import checkbox as checkbox
-from .checkbox_cards import checkbox_cards as checkbox_cards
-from .checkbox_group import checkbox_group as checkbox_group
-from .context_menu import context_menu as context_menu
-from .data_list import data_list as data_list
-from .dialog import dialog as dialog
-from .dropdown_menu import dropdown_menu as dropdown_menu
-from .dropdown_menu import menu as menu
-from .hover_card import hover_card as hover_card
-from .icon_button import icon_button as icon_button
-from .inset import inset as inset
-from .popover import popover as popover
-from .progress import progress as progress
-from .radio_cards import radio_cards as radio_cards
-from .radio_group import radio as radio
-from .radio_group import radio_group as radio_group
-from .scroll_area import scroll_area as scroll_area
-from .segmented_control import segmented_control as segmented_control
-from .select import select as select
-from .separator import divider as divider
-from .separator import separator as separator
-from .skeleton import skeleton as skeleton
-from .slider import slider as slider
-from .spinner import spinner as spinner
-from .switch import switch as switch
-from .table import table as table
-from .tabs import tabs as tabs
-from .text_area import text_area as text_area
-from .text_field import text_field as text_field
-from .tooltip import tooltip as tooltip
+from __future__ import annotations
-input = text_field
+from reflex import RADIX_THEMES_COMPONENTS_MAPPING
+from reflex.utils import lazy_loader
-__all__ = [
- "alert_dialog",
- "aspect_ratio",
- "avatar",
- "badge",
- "button",
- "callout",
- "card",
- "checkbox",
- "checkbox_cards",
- "checkbox_group",
- "context_menu",
- "data_list",
- "dialog",
- "divider",
- "dropdown_menu",
- "hover_card",
- "icon_button",
- "input",
- "inset",
- "menu",
- "popover",
- # progress is in experimental namespace until https://github.com/radix-ui/themes/pull/492
- # "progress",
- "radio",
- "radio_cards",
- "radio_group",
- "scroll_area",
- "segmented_control",
- "select",
- "separator",
- "skeleton",
- "slider",
- "spinner",
- "switch",
- "table",
- "tabs",
- "text_area",
- "text_field",
- "tooltip",
-]
+_SUBMOD_ATTRS: dict[str, list[str]] = {
+ "".join(k.split("components.radix.themes.components.")[-1]): v
+ for k, v in RADIX_THEMES_COMPONENTS_MAPPING.items()
+}
+
+__getattr__, __dir__, __all__ = lazy_loader.attach(
+ __name__,
+ submod_attrs=_SUBMOD_ATTRS,
+)
diff --git a/reflex/components/radix/themes/components/__init__.pyi b/reflex/components/radix/themes/components/__init__.pyi
new file mode 100644
index 000000000..29f15e311
--- /dev/null
+++ b/reflex/components/radix/themes/components/__init__.pyi
@@ -0,0 +1,43 @@
+"""Stub file for reflex/components/radix/themes/components/__init__.py"""
+# ------------------- DO NOT EDIT ----------------------
+# This file was generated by `reflex/utils/pyi_generator.py`!
+# ------------------------------------------------------
+
+from .alert_dialog import alert_dialog as alert_dialog
+from .aspect_ratio import aspect_ratio as aspect_ratio
+from .avatar import avatar as avatar
+from .badge import badge as badge
+from .button import button as button
+from .callout import callout as callout
+from .card import card as card
+from .checkbox import checkbox as checkbox
+from .checkbox_cards import checkbox_cards as checkbox_cards
+from .checkbox_group import checkbox_group as checkbox_group
+from .context_menu import context_menu as context_menu
+from .data_list import data_list as data_list
+from .dialog import dialog as dialog
+from .dropdown_menu import dropdown_menu as dropdown_menu
+from .dropdown_menu import menu as menu
+from .hover_card import hover_card as hover_card
+from .icon_button import icon_button as icon_button
+from .inset import inset as inset
+from .popover import popover as popover
+from .progress import progress as progress
+from .radio_cards import radio_cards as radio_cards
+from .radio_group import radio as radio
+from .radio_group import radio_group as radio_group
+from .scroll_area import scroll_area as scroll_area
+from .segmented_control import segmented_control as segmented_control
+from .select import select as select
+from .separator import divider as divider
+from .separator import separator as separator
+from .skeleton import skeleton as skeleton
+from .slider import slider as slider
+from .spinner import spinner as spinner
+from .switch import switch as switch
+from .table import table as table
+from .tabs import tabs as tabs
+from .text_area import text_area as text_area
+from .text_field import input as input
+from .text_field import text_field as text_field
+from .tooltip import tooltip as tooltip
diff --git a/reflex/components/radix/themes/components/alert_dialog.py b/reflex/components/radix/themes/components/alert_dialog.py
index b8e713bb5..f3c8ec319 100644
--- a/reflex/components/radix/themes/components/alert_dialog.py
+++ b/reflex/components/radix/themes/components/alert_dialog.py
@@ -1,10 +1,12 @@
"""Interactive components provided by @radix-ui/themes."""
-from typing import Any, Dict, Literal
-from reflex import el
+from typing import Literal
+
from reflex.components.component import ComponentNamespace
-from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.components.el import elements
+from reflex.event import EventHandler, empty_event, identity_event
+from reflex.vars.base import Var
from ..base import RadixThemesComponent, RadixThemesTriggerComponent
@@ -19,16 +21,8 @@ class AlertDialogRoot(RadixThemesComponent):
# The controlled open state of the dialog.
open: Var[bool]
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
-
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_OPEN_CHANGE: lambda e0: [e0],
- }
+ # Fired when the open state changes.
+ on_open_change: EventHandler[identity_event(bool)]
class AlertDialogTrigger(RadixThemesTriggerComponent):
@@ -37,29 +31,25 @@ class AlertDialogTrigger(RadixThemesTriggerComponent):
tag = "AlertDialog.Trigger"
-class AlertDialogContent(el.Div, RadixThemesComponent):
+class AlertDialogContent(elements.Div, RadixThemesComponent):
"""Contains the content of the dialog. This component is based on the div element."""
tag = "AlertDialog.Content"
# The size of the content.
- size: Var[LiteralContentSize]
+ size: Var[Responsive[LiteralContentSize]]
# Whether to force mount the content on open.
force_mount: Var[bool]
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
+ # Fired when the dialog is opened.
+ on_open_auto_focus: EventHandler[empty_event]
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_OPEN_AUTO_FOCUS: lambda e0: [e0],
- EventTriggers.ON_CLOSE_AUTO_FOCUS: lambda e0: [e0],
- EventTriggers.ON_ESCAPE_KEY_DOWN: lambda e0: [e0],
- }
+ # Fired when the dialog is closed.
+ on_close_auto_focus: EventHandler[empty_event]
+
+ # Fired when the escape key is pressed.
+ on_escape_key_down: EventHandler[empty_event]
class AlertDialogTitle(RadixThemesComponent):
diff --git a/reflex/components/radix/themes/components/alert_dialog.pyi b/reflex/components/radix/themes/components/alert_dialog.pyi
index a61a5bbbc..f4b674ce2 100644
--- a/reflex/components/radix/themes/components/alert_dialog.pyi
+++ b/reflex/components/radix/themes/components/alert_dialog.pyi
@@ -1,23 +1,22 @@
"""Stub file for reflex/components/radix/themes/components/alert_dialog.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Any, Dict, Literal
-from reflex import el
+
from reflex.components.component import ComponentNamespace
-from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.components.el import elements
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
+
from ..base import RadixThemesComponent, RadixThemesTriggerComponent
LiteralContentSize = Literal["1", "2", "3", "4"]
class AlertDialogRoot(RadixThemesComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
@@ -30,55 +29,23 @@ class AlertDialogRoot(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_open_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_open_change: Optional[EventType[bool]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "AlertDialogRoot":
"""Create a new component instance.
@@ -88,6 +55,7 @@ class AlertDialogRoot(RadixThemesComponent):
Args:
*children: Child components.
open: The controlled open state of the dialog.
+ on_open_change: Fired when the open state changes.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -113,52 +81,22 @@ class AlertDialogTrigger(RadixThemesTriggerComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "AlertDialogTrigger":
"""Create a new RadixThemesTriggerComponent instance.
@@ -171,118 +109,74 @@ class AlertDialogTrigger(RadixThemesTriggerComponent):
"""
...
-class AlertDialogContent(el.Div, RadixThemesComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
+class AlertDialogContent(elements.Div, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
cls,
*children,
size: Optional[
- Union[Var[Literal["1", "2", "3", "4"]], Literal["1", "2", "3", "4"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3", "4"]],
+ Literal["1", "2", "3", "4"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3", "4"]],
+ Literal["1", "2", "3", "4"],
+ ]
+ ],
+ ]
] = None,
force_mount: Optional[Union[Var[bool], bool]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_close_auto_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_escape_key_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_open_auto_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_close_auto_focus: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_escape_key_down: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_open_auto_focus: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "AlertDialogContent":
"""Create a new component instance.
@@ -293,6 +187,9 @@ class AlertDialogContent(el.Div, RadixThemesComponent):
*children: Child components.
size: The size of the content.
force_mount: Whether to force mount the content on open.
+ on_open_auto_focus: Fired when the dialog is opened.
+ on_close_auto_focus: Fired when the dialog is closed.
+ on_escape_key_down: Fired when the escape key is pressed.
access_key: Provides a hint for generating a keyboard shortcut for the current element.
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
content_editable: Indicates whether the element's content is editable.
@@ -334,52 +231,22 @@ class AlertDialogTitle(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "AlertDialogTitle":
"""Create a new component instance.
@@ -413,52 +280,22 @@ class AlertDialogDescription(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "AlertDialogDescription":
"""Create a new component instance.
@@ -492,52 +329,22 @@ class AlertDialogAction(RadixThemesTriggerComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "AlertDialogAction":
"""Create a new RadixThemesTriggerComponent instance.
@@ -562,52 +369,22 @@ class AlertDialogCancel(RadixThemesTriggerComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "AlertDialogCancel":
"""Create a new RadixThemesTriggerComponent instance.
diff --git a/reflex/components/radix/themes/components/aspect_ratio.py b/reflex/components/radix/themes/components/aspect_ratio.py
index 1b6847a18..fc8052c85 100644
--- a/reflex/components/radix/themes/components/aspect_ratio.py
+++ b/reflex/components/radix/themes/components/aspect_ratio.py
@@ -1,7 +1,8 @@
"""Interactive components provided by @radix-ui/themes."""
+
from typing import Union
-from reflex.vars import Var
+from reflex.vars.base import Var
from ..base import RadixThemesComponent
diff --git a/reflex/components/radix/themes/components/aspect_ratio.pyi b/reflex/components/radix/themes/components/aspect_ratio.pyi
index dc815991f..848d2064a 100644
--- a/reflex/components/radix/themes/components/aspect_ratio.pyi
+++ b/reflex/components/radix/themes/components/aspect_ratio.pyi
@@ -1,14 +1,14 @@
"""Stub file for reflex/components/radix/themes/components/aspect_ratio.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+from reflex.event import EventType
from reflex.style import Style
-from typing import Union
-from reflex.vars import Var
+from reflex.vars.base import Var
+
from ..base import RadixThemesComponent
class AspectRatio(RadixThemesComponent):
@@ -17,59 +17,29 @@ class AspectRatio(RadixThemesComponent):
def create( # type: ignore
cls,
*children,
- ratio: Optional[Union[Var[Union[float, int]], Union[float, int]]] = None,
+ ratio: Optional[Union[Var[Union[float, int]], float, int]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "AspectRatio":
"""Create a new component instance.
diff --git a/reflex/components/radix/themes/components/avatar.py b/reflex/components/radix/themes/components/avatar.py
index 0b64831c3..4f3956e76 100644
--- a/reflex/components/radix/themes/components/avatar.py
+++ b/reflex/components/radix/themes/components/avatar.py
@@ -2,7 +2,8 @@
from typing import Literal
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.vars.base import Var
from ..base import (
LiteralAccentColor,
@@ -22,7 +23,7 @@ class Avatar(RadixThemesComponent):
variant: Var[Literal["solid", "soft"]]
# The size of the avatar: "1" - "9"
- size: Var[LiteralSize]
+ size: Var[Responsive[LiteralSize]]
# Color theme of the avatar
color_scheme: Var[LiteralAccentColor]
diff --git a/reflex/components/radix/themes/components/avatar.pyi b/reflex/components/radix/themes/components/avatar.pyi
index 544522e73..fc42457da 100644
--- a/reflex/components/radix/themes/components/avatar.pyi
+++ b/reflex/components/radix/themes/components/avatar.pyi
@@ -1,15 +1,16 @@
"""Stub file for reflex/components/radix/themes/components/avatar.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.event import EventType
from reflex.style import Style
-from typing import Literal
-from reflex.vars import Var
-from ..base import LiteralAccentColor, LiteralRadius, RadixThemesComponent
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
LiteralSize = Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]
@@ -20,81 +21,89 @@ class Avatar(RadixThemesComponent):
cls,
*children,
variant: Optional[
- Union[Var[Literal["solid", "soft"]], Literal["solid", "soft"]]
+ Union[Literal["soft", "solid"], Var[Literal["soft", "solid"]]]
] = None,
size: Optional[
Union[
- Var[Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]
+ ],
+ Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ]
+ ],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
radius: Optional[
Union[
- Var[Literal["none", "small", "medium", "large", "full"]],
- Literal["none", "small", "medium", "large", "full"],
+ Literal["full", "large", "medium", "none", "small"],
+ Var[Literal["full", "large", "medium", "none", "small"]],
]
] = None,
src: Optional[Union[Var[str], str]] = None,
@@ -105,52 +114,22 @@ class Avatar(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Avatar":
"""Create a new component instance.
diff --git a/reflex/components/radix/themes/components/badge.py b/reflex/components/radix/themes/components/badge.py
index 587a83030..9391e53c3 100644
--- a/reflex/components/radix/themes/components/badge.py
+++ b/reflex/components/radix/themes/components/badge.py
@@ -2,8 +2,9 @@
from typing import Literal
-from reflex import el
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.components.el import elements
+from reflex.vars.base import Var
from ..base import (
LiteralAccentColor,
@@ -12,7 +13,7 @@ from ..base import (
)
-class Badge(el.Span, RadixThemesComponent):
+class Badge(elements.Span, RadixThemesComponent):
"""A stylized badge element."""
tag = "Badge"
@@ -21,7 +22,7 @@ class Badge(el.Span, RadixThemesComponent):
variant: Var[Literal["solid", "soft", "surface", "outline"]]
# The size of the badge
- size: Var[Literal["1", "2", "3"]]
+ size: Var[Responsive[Literal["1", "2", "3"]]]
# Color theme of the badge
color_scheme: Var[LiteralAccentColor]
diff --git a/reflex/components/radix/themes/components/badge.pyi b/reflex/components/radix/themes/components/badge.pyi
index 758630905..405b7b835 100644
--- a/reflex/components/radix/themes/components/badge.pyi
+++ b/reflex/components/radix/themes/components/badge.pyi
@@ -1,18 +1,19 @@
"""Stub file for reflex/components/radix/themes/components/badge.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Literal
-from reflex import el
-from reflex.vars import Var
-from ..base import LiteralAccentColor, LiteralRadius, RadixThemesComponent
-class Badge(el.Span, RadixThemesComponent):
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.components.el import elements
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
+
+class Badge(elements.Span, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
@@ -20,174 +21,136 @@ class Badge(el.Span, RadixThemesComponent):
*children,
variant: Optional[
Union[
- Var[Literal["solid", "soft", "surface", "outline"]],
- Literal["solid", "soft", "surface", "outline"],
+ Literal["outline", "soft", "solid", "surface"],
+ Var[Literal["outline", "soft", "solid", "surface"]],
]
] = None,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
radius: Optional[
Union[
- Var[Literal["none", "small", "medium", "large", "full"]],
- Literal["none", "small", "medium", "large", "full"],
+ Literal["full", "large", "medium", "none", "small"],
+ Var[Literal["full", "large", "medium", "none", "small"]],
]
] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Badge":
"""Create a new component instance.
diff --git a/reflex/components/radix/themes/components/button.py b/reflex/components/radix/themes/components/button.py
index 0e8f95345..cb44ee684 100644
--- a/reflex/components/radix/themes/components/button.py
+++ b/reflex/components/radix/themes/components/button.py
@@ -2,8 +2,9 @@
from typing import Literal
-from reflex import el
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.components.el import elements
+from reflex.vars.base import Var
from ..base import (
LiteralAccentColor,
@@ -16,7 +17,7 @@ from ..base import (
LiteralButtonSize = Literal["1", "2", "3", "4"]
-class Button(el.Button, RadixLoadingProp, RadixThemesComponent):
+class Button(elements.Button, RadixLoadingProp, RadixThemesComponent):
"""Trigger an action or event, such as submitting a form or displaying a dialog."""
tag = "Button"
@@ -25,7 +26,7 @@ class Button(el.Button, RadixLoadingProp, RadixThemesComponent):
as_child: Var[bool]
# Button size "1" - "4"
- size: Var[LiteralButtonSize]
+ size: Var[Responsive[LiteralButtonSize]]
# Variant of button: "solid" | "soft" | "outline" | "ghost"
variant: Var[LiteralVariant]
diff --git a/reflex/components/radix/themes/components/button.pyi b/reflex/components/radix/themes/components/button.pyi
index 617b7b389..f9702d3b5 100644
--- a/reflex/components/radix/themes/components/button.pyi
+++ b/reflex/components/radix/themes/components/button.pyi
@@ -1,26 +1,24 @@
"""Stub file for reflex/components/radix/themes/components/button.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.components.el import elements
+from reflex.event import EventType
from reflex.style import Style
-from typing import Literal
-from reflex import el
-from reflex.vars import Var
+from reflex.vars.base import Var
+
from ..base import (
- LiteralAccentColor,
- LiteralRadius,
- LiteralVariant,
RadixLoadingProp,
RadixThemesComponent,
)
LiteralButtonSize = Literal["1", "2", "3", "4"]
-class Button(el.Button, RadixLoadingProp, RadixThemesComponent):
+class Button(elements.Button, RadixLoadingProp, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
@@ -28,148 +26,131 @@ class Button(el.Button, RadixLoadingProp, RadixThemesComponent):
*children,
as_child: Optional[Union[Var[bool], bool]] = None,
size: Optional[
- Union[Var[Literal["1", "2", "3", "4"]], Literal["1", "2", "3", "4"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3", "4"]],
+ Literal["1", "2", "3", "4"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3", "4"]],
+ Literal["1", "2", "3", "4"],
+ ]
+ ],
+ ]
] = None,
variant: Optional[
Union[
- Var[Literal["classic", "solid", "soft", "surface", "outline", "ghost"]],
- Literal["classic", "solid", "soft", "surface", "outline", "ghost"],
+ Literal["classic", "ghost", "outline", "soft", "solid", "surface"],
+ Var[Literal["classic", "ghost", "outline", "soft", "solid", "surface"]],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
radius: Optional[
Union[
- Var[Literal["none", "small", "medium", "large", "full"]],
- Literal["none", "small", "medium", "large", "full"],
+ Literal["full", "large", "medium", "none", "small"],
+ Var[Literal["full", "large", "medium", "none", "small"]],
]
] = None,
- auto_focus: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ auto_focus: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
disabled: Optional[Union[Var[bool], bool]] = None,
- form: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- form_action: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ form: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ form_action: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
form_enc_type: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- form_method: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ form_method: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
form_no_validate: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- form_target: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- name: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- type: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- value: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ form_target: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ name: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ type: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ value: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
loading: Optional[Union[Var[bool], bool]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
@@ -177,52 +158,22 @@ class Button(el.Button, RadixLoadingProp, RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Button":
"""Create a new component instance.
diff --git a/reflex/components/radix/themes/components/callout.py b/reflex/components/radix/themes/components/callout.py
index 5eaf1cac0..926e0ad54 100644
--- a/reflex/components/radix/themes/components/callout.py
+++ b/reflex/components/radix/themes/components/callout.py
@@ -3,10 +3,11 @@
from typing import Literal, Union
import reflex as rx
-from reflex import el
from reflex.components.component import Component, ComponentNamespace
+from reflex.components.core.breakpoints import Responsive
+from reflex.components.el import elements
from reflex.components.lucide.icon import Icon
-from reflex.vars import Var
+from reflex.vars.base import Var
from ..base import (
LiteralAccentColor,
@@ -16,7 +17,7 @@ from ..base import (
CalloutVariant = Literal["soft", "surface", "outline"]
-class CalloutRoot(el.Div, RadixThemesComponent):
+class CalloutRoot(elements.Div, RadixThemesComponent):
"""Groups Icon and Text parts of a Callout."""
tag = "Callout.Root"
@@ -25,7 +26,7 @@ class CalloutRoot(el.Div, RadixThemesComponent):
as_child: Var[bool]
# Size "1" - "3"
- size: Var[Literal["1", "2", "3"]]
+ size: Var[Responsive[Literal["1", "2", "3"]]]
# Variant of button: "soft" | "surface" | "outline"
variant: Var[CalloutVariant]
@@ -37,13 +38,13 @@ class CalloutRoot(el.Div, RadixThemesComponent):
high_contrast: Var[bool]
-class CalloutIcon(el.Div, RadixThemesComponent):
+class CalloutIcon(elements.Div, RadixThemesComponent):
"""Provides width and height for the icon associated with the callout."""
tag = "Callout.Icon"
-class CalloutText(el.P, RadixThemesComponent):
+class CalloutText(elements.P, RadixThemesComponent):
"""Renders the callout text. This component is based on the p element."""
tag = "Callout.Text"
diff --git a/reflex/components/radix/themes/components/callout.pyi b/reflex/components/radix/themes/components/callout.pyi
index ff7cf0b00..18ae5a357 100644
--- a/reflex/components/radix/themes/components/callout.pyi
+++ b/reflex/components/radix/themes/components/callout.pyi
@@ -1,23 +1,22 @@
"""Stub file for reflex/components/radix/themes/components/callout.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+
+from reflex.components.component import ComponentNamespace
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.components.el import elements
+from reflex.event import EventType
from reflex.style import Style
-from typing import Literal, Union
-import reflex as rx
-from reflex import el
-from reflex.components.component import Component, ComponentNamespace
-from reflex.components.lucide.icon import Icon
-from reflex.vars import Var
-from ..base import LiteralAccentColor, RadixThemesComponent
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
CalloutVariant = Literal["soft", "surface", "outline"]
-class CalloutRoot(el.Div, RadixThemesComponent):
+class CalloutRoot(elements.Div, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
@@ -25,169 +24,131 @@ class CalloutRoot(el.Div, RadixThemesComponent):
*children,
as_child: Optional[Union[Var[bool], bool]] = None,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
variant: Optional[
Union[
- Var[Literal["soft", "surface", "outline"]],
- Literal["soft", "surface", "outline"],
+ Literal["outline", "soft", "surface"],
+ Var[Literal["outline", "soft", "surface"]],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "CalloutRoot":
"""Create a new component instance.
@@ -230,104 +191,58 @@ class CalloutRoot(el.Div, RadixThemesComponent):
"""
...
-class CalloutIcon(el.Div, RadixThemesComponent):
+class CalloutIcon(elements.Div, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "CalloutIcon":
"""Create a new component instance.
@@ -365,104 +280,58 @@ class CalloutIcon(el.Div, RadixThemesComponent):
"""
...
-class CalloutText(el.P, RadixThemesComponent):
+class CalloutText(elements.P, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "CalloutText":
"""Create a new component instance.
@@ -510,169 +379,131 @@ class Callout(CalloutRoot):
icon: Optional[Union[Var[str], str]] = None,
as_child: Optional[Union[Var[bool], bool]] = None,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
variant: Optional[
Union[
- Var[Literal["soft", "surface", "outline"]],
- Literal["soft", "surface", "outline"],
+ Literal["outline", "soft", "surface"],
+ Var[Literal["outline", "soft", "surface"]],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Callout":
"""Create a callout component.
@@ -726,169 +557,131 @@ class CalloutNamespace(ComponentNamespace):
icon: Optional[Union[Var[str], str]] = None,
as_child: Optional[Union[Var[bool], bool]] = None,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
variant: Optional[
Union[
- Var[Literal["soft", "surface", "outline"]],
- Literal["soft", "surface", "outline"],
+ Literal["outline", "soft", "surface"],
+ Var[Literal["outline", "soft", "surface"]],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Callout":
"""Create a callout component.
diff --git a/reflex/components/radix/themes/components/card.py b/reflex/components/radix/themes/components/card.py
index ab4cf2b88..4983cdd41 100644
--- a/reflex/components/radix/themes/components/card.py
+++ b/reflex/components/radix/themes/components/card.py
@@ -1,15 +1,17 @@
"""Interactive components provided by @radix-ui/themes."""
+
from typing import Literal
-from reflex import el
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.components.el import elements
+from reflex.vars.base import Var
from ..base import (
RadixThemesComponent,
)
-class Card(el.Div, RadixThemesComponent):
+class Card(elements.Div, RadixThemesComponent):
"""Container that groups related content and actions."""
tag = "Card"
@@ -18,7 +20,7 @@ class Card(el.Div, RadixThemesComponent):
as_child: Var[bool]
# Card size: "1" - "5"
- size: Var[Literal["1", "2", "3", "4", "5"]]
+ size: Var[Responsive[Literal["1", "2", "3", "4", "5"],]]
# Variant of Card: "solid" | "soft" | "outline" | "ghost"
variant: Var[Literal["surface", "classic", "ghost"]]
diff --git a/reflex/components/radix/themes/components/card.pyi b/reflex/components/radix/themes/components/card.pyi
index b6df648cb..dc45bc226 100644
--- a/reflex/components/radix/themes/components/card.pyi
+++ b/reflex/components/radix/themes/components/card.pyi
@@ -1,18 +1,19 @@
"""Stub file for reflex/components/radix/themes/components/card.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.components.el import elements
+from reflex.event import EventType
from reflex.style import Style
-from typing import Literal
-from reflex import el
-from reflex.vars import Var
+from reflex.vars.base import Var
+
from ..base import RadixThemesComponent
-class Card(el.Div, RadixThemesComponent):
+class Card(elements.Div, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
@@ -21,107 +22,68 @@ class Card(el.Div, RadixThemesComponent):
as_child: Optional[Union[Var[bool], bool]] = None,
size: Optional[
Union[
- Var[Literal["1", "2", "3", "4", "5"]], Literal["1", "2", "3", "4", "5"]
+ Breakpoints[str, Literal["1", "2", "3", "4", "5"]],
+ Literal["1", "2", "3", "4", "5"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3", "4", "5"]],
+ Literal["1", "2", "3", "4", "5"],
+ ]
+ ],
]
] = None,
variant: Optional[
Union[
- Var[Literal["surface", "classic", "ghost"]],
- Literal["surface", "classic", "ghost"],
+ Literal["classic", "ghost", "surface"],
+ Var[Literal["classic", "ghost", "surface"]],
]
] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Card":
"""Create a new component instance.
diff --git a/reflex/components/radix/themes/components/checkbox.py b/reflex/components/radix/themes/components/checkbox.py
index 250a1da4c..2944b1f11 100644
--- a/reflex/components/radix/themes/components/checkbox.py
+++ b/reflex/components/radix/themes/components/checkbox.py
@@ -1,12 +1,13 @@
"""Interactive components provided by @radix-ui/themes."""
-from typing import Any, Dict, Literal
+from typing import Literal
from reflex.components.component import Component, ComponentNamespace
+from reflex.components.core.breakpoints import Responsive
from reflex.components.radix.themes.layout.flex import Flex
from reflex.components.radix.themes.typography.text import Text
-from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.event import EventHandler, identity_event
+from reflex.vars.base import LiteralVar, Var
from ..base import (
LiteralAccentColor,
@@ -27,7 +28,7 @@ class Checkbox(RadixThemesComponent):
as_child: Var[bool]
# Checkbox size "1" - "3"
- size: Var[LiteralCheckboxSize]
+ size: Var[Responsive[LiteralCheckboxSize]]
# Variant of checkbox: "classic" | "surface" | "soft"
variant: Var[LiteralCheckboxVariant]
@@ -59,16 +60,8 @@ class Checkbox(RadixThemesComponent):
# Props to rename
_rename_props = {"onChange": "onCheckedChange"}
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
-
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_CHANGE: lambda e0: [e0],
- }
+ # Fired when the checkbox is checked or unchecked.
+ on_change: EventHandler[identity_event(bool)]
class HighLevelCheckbox(RadixThemesComponent):
@@ -118,19 +111,11 @@ class HighLevelCheckbox(RadixThemesComponent):
# Props to rename
_rename_props = {"onChange": "onCheckedChange"}
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
-
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_CHANGE: lambda e0: [e0],
- }
+ # Fired when the checkbox is checked or unchecked.
+ on_change: EventHandler[identity_event(bool)]
@classmethod
- def create(cls, text: Var[str] = Var.create_safe(""), **props) -> Component:
+ def create(cls, text: Var[str] = LiteralVar.create(""), **props) -> Component:
"""Create a checkbox with a label.
Args:
diff --git a/reflex/components/radix/themes/components/checkbox.pyi b/reflex/components/radix/themes/components/checkbox.pyi
index 229fca26a..8f69a0f73 100644
--- a/reflex/components/radix/themes/components/checkbox.pyi
+++ b/reflex/components/radix/themes/components/checkbox.pyi
@@ -1,25 +1,22 @@
"""Stub file for reflex/components/radix/themes/components/checkbox.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+
+from reflex.components.component import ComponentNamespace
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.event import EventType
from reflex.style import Style
-from typing import Any, Dict, Literal
-from reflex.components.component import Component, ComponentNamespace
-from reflex.components.radix.themes.layout.flex import Flex
-from reflex.components.radix.themes.typography.text import Text
-from reflex.constants import EventTriggers
-from reflex.vars import Var
-from ..base import LiteralAccentColor, LiteralSpacing, RadixThemesComponent
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
LiteralCheckboxSize = Literal["1", "2", "3"]
LiteralCheckboxVariant = Literal["classic", "surface", "soft"]
class Checkbox(RadixThemesComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
@@ -27,73 +24,81 @@ class Checkbox(RadixThemesComponent):
*children,
as_child: Optional[Union[Var[bool], bool]] = None,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
variant: Optional[
Union[
- Var[Literal["classic", "surface", "soft"]],
- Literal["classic", "surface", "soft"],
+ Literal["classic", "soft", "surface"],
+ Var[Literal["classic", "soft", "surface"]],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
@@ -110,55 +115,23 @@ class Checkbox(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_change: Optional[EventType[bool]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Checkbox":
"""Create a new component instance.
@@ -178,6 +151,7 @@ class Checkbox(RadixThemesComponent):
required: Whether the checkbox is required
name: The name of the checkbox control when submitting the form.
value: The value of the checkbox control when submitting the form.
+ on_change: Props to rename Fired when the checkbox is checked or unchecked.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -192,7 +166,6 @@ class Checkbox(RadixThemesComponent):
...
class HighLevelCheckbox(RadixThemesComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
@@ -201,79 +174,79 @@ class HighLevelCheckbox(RadixThemesComponent):
text: Optional[Union[Var[str], str]] = None,
spacing: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
]
] = None,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[Literal["1", "2", "3"], Var[Literal["1", "2", "3"]]]
] = None,
as_child: Optional[Union[Var[bool], bool]] = None,
variant: Optional[
Union[
- Var[Literal["classic", "surface", "soft"]],
- Literal["classic", "surface", "soft"],
+ Literal["classic", "soft", "surface"],
+ Var[Literal["classic", "soft", "surface"]],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
@@ -290,55 +263,23 @@ class HighLevelCheckbox(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_change: Optional[EventType[bool]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "HighLevelCheckbox":
"""Create a checkbox with a label.
@@ -357,6 +298,7 @@ class HighLevelCheckbox(RadixThemesComponent):
required: Whether the checkbox is required
name: The name of the checkbox control when submitting the form.
value: The value of the checkbox control when submitting the form.
+ on_change: Props to rename Fired when the checkbox is checked or unchecked.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -377,79 +319,79 @@ class CheckboxNamespace(ComponentNamespace):
text: Optional[Union[Var[str], str]] = None,
spacing: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
]
] = None,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[Literal["1", "2", "3"], Var[Literal["1", "2", "3"]]]
] = None,
as_child: Optional[Union[Var[bool], bool]] = None,
variant: Optional[
Union[
- Var[Literal["classic", "surface", "soft"]],
- Literal["classic", "surface", "soft"],
+ Literal["classic", "soft", "surface"],
+ Var[Literal["classic", "soft", "surface"]],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
@@ -466,55 +408,23 @@ class CheckboxNamespace(ComponentNamespace):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_change: Optional[EventType[bool]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "HighLevelCheckbox":
"""Create a checkbox with a label.
@@ -533,6 +443,7 @@ class CheckboxNamespace(ComponentNamespace):
required: Whether the checkbox is required
name: The name of the checkbox control when submitting the form.
value: The value of the checkbox control when submitting the form.
+ on_change: Props to rename Fired when the checkbox is checked or unchecked.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
diff --git a/reflex/components/radix/themes/components/checkbox_cards.py b/reflex/components/radix/themes/components/checkbox_cards.py
index 50e6a2b1d..5f5fc3ae3 100644
--- a/reflex/components/radix/themes/components/checkbox_cards.py
+++ b/reflex/components/radix/themes/components/checkbox_cards.py
@@ -3,7 +3,8 @@
from types import SimpleNamespace
from typing import Literal, Union
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.vars.base import Var
from ..base import LiteralAccentColor, RadixThemesComponent
@@ -14,7 +15,7 @@ class CheckboxCardsRoot(RadixThemesComponent):
tag = "CheckboxCards.Root"
# The size of the checkbox cards: "1" | "2" | "3"
- size: Var[Literal["1", "2", "3"]]
+ size: Var[Responsive[Literal["1", "2", "3"]]]
# Variant of button: "classic" | "surface" | "soft"
variant: Var[Literal["classic", "surface"]]
@@ -26,10 +27,14 @@ class CheckboxCardsRoot(RadixThemesComponent):
high_contrast: Var[bool]
# The number of columns:
- columns: Var[Union[str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]]]
+ columns: Var[
+ Responsive[Union[str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]]]
+ ]
# The gap between the checkbox cards:
- gap: Var[Union[str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]]]
+ gap: Var[
+ Responsive[Union[str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]]]
+ ]
class CheckboxCardsItem(RadixThemesComponent):
diff --git a/reflex/components/radix/themes/components/checkbox_cards.pyi b/reflex/components/radix/themes/components/checkbox_cards.pyi
index 535bec92f..062fc1357 100644
--- a/reflex/components/radix/themes/components/checkbox_cards.pyi
+++ b/reflex/components/radix/themes/components/checkbox_cards.pyi
@@ -1,16 +1,17 @@
"""Stub file for reflex/components/radix/themes/components/checkbox_cards.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
from types import SimpleNamespace
-from typing import Literal, Union
-from reflex.vars import Var
-from ..base import LiteralAccentColor, RadixThemesComponent
+from typing import Any, Dict, Literal, Optional, Union, overload
+
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
class CheckboxCardsRoot(RadixThemesComponent):
@overload
@@ -19,84 +20,126 @@ class CheckboxCardsRoot(RadixThemesComponent):
cls,
*children,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
variant: Optional[
- Union[Var[Literal["classic", "surface"]], Literal["classic", "surface"]]
+ Union[Literal["classic", "surface"], Var[Literal["classic", "surface"]]]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
columns: Optional[
Union[
- Var[Union[str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]]],
- Union[str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[
+ str,
+ Union[Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"], str],
+ ],
+ Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Union[
+ Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ str,
+ ],
+ ],
+ Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ str,
+ ]
+ ],
+ str,
]
] = None,
gap: Optional[
Union[
- Var[Union[str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]]],
- Union[str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[
+ str,
+ Union[Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"], str],
+ ],
+ Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Union[
+ Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ str,
+ ],
+ ],
+ Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ str,
+ ]
+ ],
+ str,
]
] = None,
style: Optional[Style] = None,
@@ -105,52 +148,22 @@ class CheckboxCardsRoot(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "CheckboxCardsRoot":
"""Create a new component instance.
@@ -190,52 +203,22 @@ class CheckboxCardsItem(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "CheckboxCardsItem":
"""Create a new component instance.
diff --git a/reflex/components/radix/themes/components/checkbox_group.py b/reflex/components/radix/themes/components/checkbox_group.py
index 73bc0f53f..f6379e588 100644
--- a/reflex/components/radix/themes/components/checkbox_group.py
+++ b/reflex/components/radix/themes/components/checkbox_group.py
@@ -1,9 +1,10 @@
"""Components for the CheckboxGroup component of Radix Themes."""
from types import SimpleNamespace
-from typing import Literal
+from typing import List, Literal
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.vars.base import Var
from ..base import LiteralAccentColor, RadixThemesComponent
@@ -11,10 +12,10 @@ from ..base import LiteralAccentColor, RadixThemesComponent
class CheckboxGroupRoot(RadixThemesComponent):
"""Root element for a CheckboxGroup component."""
- tag = "CheckboxGroup"
+ tag = "CheckboxGroup.Root"
- #
- size: Var[Literal["1", "2", "3"]]
+ # Use the size prop to control the checkbox size.
+ size: Var[Responsive[Literal["1", "2", "3"]]]
# Variant of button: "classic" | "surface" | "soft"
variant: Var[Literal["classic", "surface", "soft"]]
@@ -25,12 +26,24 @@ class CheckboxGroupRoot(RadixThemesComponent):
# Uses a higher contrast color for the component.
high_contrast: Var[bool]
+ # determines which checkboxes, if any, are checked by default.
+ default_value: Var[List[str]]
+
+ # used to assign a name to the entire group of checkboxes
+ name: Var[str]
+
class CheckboxGroupItem(RadixThemesComponent):
"""An item in the CheckboxGroup component."""
tag = "CheckboxGroup.Item"
+ # specifies the value associated with a particular checkbox option.
+ value: Var[str]
+
+ # Use the native disabled attribute to create a disabled checkbox.
+ disabled: Var[bool]
+
class CheckboxGroup(SimpleNamespace):
"""CheckboxGroup components namespace."""
diff --git a/reflex/components/radix/themes/components/checkbox_group.pyi b/reflex/components/radix/themes/components/checkbox_group.pyi
index b77e48f9c..363be0599 100644
--- a/reflex/components/radix/themes/components/checkbox_group.pyi
+++ b/reflex/components/radix/themes/components/checkbox_group.pyi
@@ -1,16 +1,17 @@
"""Stub file for reflex/components/radix/themes/components/checkbox_group.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
from types import SimpleNamespace
-from typing import Literal
-from reflex.vars import Var
-from ..base import LiteralAccentColor, RadixThemesComponent
+from typing import Any, Dict, List, Literal, Optional, Union, overload
+
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
class CheckboxGroupRoot(RadixThemesComponent):
@overload
@@ -19,129 +20,109 @@ class CheckboxGroupRoot(RadixThemesComponent):
cls,
*children,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
variant: Optional[
Union[
- Var[Literal["classic", "surface", "soft"]],
- Literal["classic", "surface", "soft"],
+ Literal["classic", "soft", "surface"],
+ Var[Literal["classic", "soft", "surface"]],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
+ default_value: Optional[Union[List[str], Var[List[str]]]] = None,
+ name: Optional[Union[Var[str], str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "CheckboxGroupRoot":
"""Create a new component instance.
@@ -150,10 +131,12 @@ class CheckboxGroupRoot(RadixThemesComponent):
Args:
*children: Child components.
- size:
+ size: Use the size prop to control the checkbox size.
variant: Variant of button: "classic" | "surface" | "soft"
color_scheme: Override theme color for button
high_contrast: Uses a higher contrast color for the component.
+ default_value: determines which checkboxes, if any, are checked by default.
+ name: used to assign a name to the entire group of checkboxes
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -173,58 +156,30 @@ class CheckboxGroupItem(RadixThemesComponent):
def create( # type: ignore
cls,
*children,
+ value: Optional[Union[Var[str], str]] = None,
+ disabled: Optional[Union[Var[bool], bool]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "CheckboxGroupItem":
"""Create a new component instance.
@@ -233,6 +188,8 @@ class CheckboxGroupItem(RadixThemesComponent):
Args:
*children: Child components.
+ value: specifies the value associated with a particular checkbox option.
+ disabled: Use the native disabled attribute to create a disabled checkbox.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
diff --git a/reflex/components/radix/themes/components/context_menu.py b/reflex/components/radix/themes/components/context_menu.py
index 7631d7970..3eb54a457 100644
--- a/reflex/components/radix/themes/components/context_menu.py
+++ b/reflex/components/radix/themes/components/context_menu.py
@@ -1,9 +1,11 @@
"""Interactive components provided by @radix-ui/themes."""
-from typing import Any, Dict, List, Literal
+
+from typing import List, Literal
from reflex.components.component import ComponentNamespace
-from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.event import EventHandler, empty_event, identity_event
+from reflex.vars.base import Var
from ..base import (
LiteralAccentColor,
@@ -21,16 +23,8 @@ class ContextMenuRoot(RadixThemesComponent):
_invalid_children: List[str] = ["ContextMenuItem"]
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
-
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_OPEN_CHANGE: lambda e0: [e0],
- }
+ # Fired when the open state changes.
+ on_open_change: EventHandler[identity_event(bool)]
class ContextMenuTrigger(RadixThemesComponent):
@@ -52,7 +46,7 @@ class ContextMenuContent(RadixThemesComponent):
tag = "ContextMenu.Content"
# Button size "1" - "4"
- size: Var[Literal["1", "2"]]
+ size: Var[Responsive[Literal["1", "2"]]]
# Variant of button: "solid" | "soft" | "outline" | "ghost"
variant: Var[Literal["solid", "soft"]]
@@ -69,20 +63,20 @@ class ContextMenuContent(RadixThemesComponent):
# When true, overrides the side and aligns preferences to prevent collisions with boundary edges.
avoid_collisions: Var[bool]
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
+ # Fired when the context menu is closed.
+ on_close_auto_focus: EventHandler[empty_event]
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_CLOSE_AUTO_FOCUS: lambda e0: [e0],
- EventTriggers.ON_ESCAPE_KEY_DOWN: lambda e0: [e0],
- EventTriggers.ON_POINTER_DOWN_OUTSIDE: lambda e0: [e0],
- EventTriggers.ON_FOCUS_OUTSIDE: lambda e0: [e0],
- EventTriggers.ON_INTERACT_OUTSIDE: lambda e0: [e0],
- }
+ # Fired when the escape key is pressed.
+ on_escape_key_down: EventHandler[empty_event]
+
+ # Fired when a pointer down event happens outside the context menu.
+ on_pointer_down_outside: EventHandler[empty_event]
+
+ # Fired when focus moves outside the context menu.
+ on_focus_outside: EventHandler[empty_event]
+
+ # Fired when interacting outside the context menu.
+ on_interact_outside: EventHandler[empty_event]
class ContextMenuSub(RadixThemesComponent):
@@ -112,19 +106,17 @@ class ContextMenuSubContent(RadixThemesComponent):
_valid_parents: List[str] = ["ContextMenuSub"]
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
+ # Fired when the escape key is pressed.
+ on_escape_key_down: EventHandler[empty_event]
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_ESCAPE_KEY_DOWN: lambda e0: [e0],
- EventTriggers.ON_POINTER_DOWN_OUTSIDE: lambda e0: [e0],
- EventTriggers.ON_FOCUS_OUTSIDE: lambda e0: [e0],
- EventTriggers.ON_INTERACT_OUTSIDE: lambda e0: [e0],
- }
+ # Fired when a pointer down event happens outside the context menu.
+ on_pointer_down_outside: EventHandler[empty_event]
+
+ # Fired when focus moves outside the context menu.
+ on_focus_outside: EventHandler[empty_event]
+
+ # Fired when interacting outside the context menu.
+ on_interact_outside: EventHandler[empty_event]
class ContextMenuItem(RadixThemesComponent):
diff --git a/reflex/components/radix/themes/components/context_menu.pyi b/reflex/components/radix/themes/components/context_menu.pyi
index 9e819f911..bfb88b303 100644
--- a/reflex/components/radix/themes/components/context_menu.pyi
+++ b/reflex/components/radix/themes/components/context_menu.pyi
@@ -1,20 +1,19 @@
"""Stub file for reflex/components/radix/themes/components/context_menu.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Any, Dict, List, Literal
+
from reflex.components.component import ComponentNamespace
-from reflex.constants import EventTriggers
-from reflex.vars import Var
-from ..base import LiteralAccentColor, RadixThemesComponent
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
class ContextMenuRoot(RadixThemesComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
@@ -27,55 +26,23 @@ class ContextMenuRoot(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_open_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_open_change: Optional[EventType[bool]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ContextMenuRoot":
"""Create a new component instance.
@@ -85,6 +52,7 @@ class ContextMenuRoot(RadixThemesComponent):
Args:
*children: Child components.
modal: The modality of the context menu. When set to true, interaction with outside elements will be disabled and only menu content will be visible to screen readers.
+ on_open_change: Fired when the open state changes.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -111,52 +79,22 @@ class ContextMenuTrigger(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ContextMenuTrigger":
"""Create a new component instance.
@@ -180,75 +118,80 @@ class ContextMenuTrigger(RadixThemesComponent):
...
class ContextMenuContent(RadixThemesComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- size: Optional[Union[Var[Literal["1", "2"]], Literal["1", "2"]]] = None,
+ size: Optional[
+ Union[
+ Breakpoints[str, Literal["1", "2"]],
+ Literal["1", "2"],
+ Var[Union[Breakpoints[str, Literal["1", "2"]], Literal["1", "2"]]],
+ ]
+ ] = None,
variant: Optional[
- Union[Var[Literal["solid", "soft"]], Literal["solid", "soft"]]
+ Union[Literal["soft", "solid"], Var[Literal["soft", "solid"]]]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
@@ -261,67 +204,27 @@ class ContextMenuContent(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_close_auto_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_escape_key_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus_outside: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_interact_outside: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_pointer_down_outside: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_close_auto_focus: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_escape_key_down: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_focus_outside: Optional[EventType[[]]] = None,
+ on_interact_outside: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_pointer_down_outside: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ContextMenuContent":
"""Create a new component instance.
@@ -336,6 +239,11 @@ class ContextMenuContent(RadixThemesComponent):
high_contrast: Whether to render the button with higher contrast color against background
align_offset: The vertical distance in pixels from the anchor.
avoid_collisions: When true, overrides the side and aligns preferences to prevent collisions with boundary edges.
+ on_close_auto_focus: Fired when the context menu is closed.
+ on_escape_key_down: Fired when the escape key is pressed.
+ on_pointer_down_outside: Fired when a pointer down event happens outside the context menu.
+ on_focus_outside: Fired when focus moves outside the context menu.
+ on_interact_outside: Fired when interacting outside the context menu.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -361,52 +269,22 @@ class ContextMenuSub(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ContextMenuSub":
"""Create a new component instance.
@@ -441,52 +319,22 @@ class ContextMenuSubTrigger(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ContextMenuSubTrigger":
"""Create a new component instance.
@@ -510,7 +358,6 @@ class ContextMenuSubTrigger(RadixThemesComponent):
...
class ContextMenuSubContent(RadixThemesComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
@@ -523,64 +370,26 @@ class ContextMenuSubContent(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_escape_key_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus_outside: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_interact_outside: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_pointer_down_outside: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_escape_key_down: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_focus_outside: Optional[EventType[[]]] = None,
+ on_interact_outside: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_pointer_down_outside: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ContextMenuSubContent":
"""Create a new component instance.
@@ -590,6 +399,10 @@ class ContextMenuSubContent(RadixThemesComponent):
Args:
*children: Child components.
loop: When true, keyboard navigation will loop from last item to first, and vice versa.
+ on_escape_key_down: Fired when the escape key is pressed.
+ on_pointer_down_outside: Fired when a pointer down event happens outside the context menu.
+ on_focus_outside: Fired when focus moves outside the context menu.
+ on_interact_outside: Fired when interacting outside the context menu.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -611,63 +424,63 @@ class ContextMenuItem(RadixThemesComponent):
*children,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
@@ -678,52 +491,22 @@ class ContextMenuItem(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ContextMenuItem":
"""Create a new component instance.
@@ -759,52 +542,22 @@ class ContextMenuSeparator(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ContextMenuSeparator":
"""Create a new component instance.
diff --git a/reflex/components/radix/themes/components/data_list.py b/reflex/components/radix/themes/components/data_list.py
index 44d797edd..05d4af074 100644
--- a/reflex/components/radix/themes/components/data_list.py
+++ b/reflex/components/radix/themes/components/data_list.py
@@ -3,7 +3,8 @@
from types import SimpleNamespace
from typing import Literal
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.vars.base import Var
from ..base import LiteralAccentColor, RadixThemesComponent
@@ -14,13 +15,13 @@ class DataListRoot(RadixThemesComponent):
tag = "DataList.Root"
# The orientation of the data list item: "horizontal" | "vertical"
- orientation: Var[Literal["horizontal", "vertical"]]
+ orientation: Var[Responsive[Literal["horizontal", "vertical"]]]
# The size of the data list item: "1" | "2" | "3"
- size: Var[Literal["1", "2", "3"]]
+ size: Var[Responsive[Literal["1", "2", "3"]]]
# Trims the leading whitespace from the start or end of the text.
- trim: Var[Literal["normal", "start", "end", "both"]]
+ trim: Var[Responsive[Literal["normal", "start", "end", "both"]]]
class DataListItem(RadixThemesComponent):
@@ -28,7 +29,8 @@ class DataListItem(RadixThemesComponent):
tag = "DataList.Item"
- align: Var[Literal["start", "center", "end", "baseline", "stretch"]]
+ # The alignment of the data list item within its container.
+ align: Var[Responsive[Literal["start", "center", "end", "baseline", "stretch"]]]
class DataListLabel(RadixThemesComponent):
@@ -36,12 +38,16 @@ class DataListLabel(RadixThemesComponent):
tag = "DataList.Label"
- width: Var[str]
+ # The width of the component
+ width: Var[Responsive[str]]
- min_width: Var[str]
+ # The minimum width of the component
+ min_width: Var[Responsive[str]]
- max_width: Var[str]
+ # The maximum width of the component
+ max_width: Var[Responsive[str]]
+ # The color scheme for the DataList component.
color_scheme: Var[LiteralAccentColor]
diff --git a/reflex/components/radix/themes/components/data_list.pyi b/reflex/components/radix/themes/components/data_list.pyi
index 0bf459fa0..342fa6e77 100644
--- a/reflex/components/radix/themes/components/data_list.pyi
+++ b/reflex/components/radix/themes/components/data_list.pyi
@@ -1,16 +1,17 @@
"""Stub file for reflex/components/radix/themes/components/data_list.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
from types import SimpleNamespace
-from typing import Literal
-from reflex.vars import Var
-from ..base import LiteralAccentColor, RadixThemesComponent
+from typing import Any, Dict, Literal, Optional, Union, overload
+
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
class DataListRoot(RadixThemesComponent):
@overload
@@ -20,17 +21,37 @@ class DataListRoot(RadixThemesComponent):
*children,
orientation: Optional[
Union[
- Var[Literal["horizontal", "vertical"]],
+ Breakpoints[str, Literal["horizontal", "vertical"]],
Literal["horizontal", "vertical"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["horizontal", "vertical"]],
+ Literal["horizontal", "vertical"],
+ ]
+ ],
]
] = None,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
trim: Optional[
Union[
- Var[Literal["normal", "start", "end", "both"]],
- Literal["normal", "start", "end", "both"],
+ Breakpoints[str, Literal["both", "end", "normal", "start"]],
+ Literal["both", "end", "normal", "start"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["both", "end", "normal", "start"]],
+ Literal["both", "end", "normal", "start"],
+ ]
+ ],
]
] = None,
style: Optional[Style] = None,
@@ -39,52 +60,22 @@ class DataListRoot(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DataListRoot":
"""Create a new component instance.
@@ -117,8 +108,19 @@ class DataListItem(RadixThemesComponent):
*children,
align: Optional[
Union[
- Var[Literal["start", "center", "end", "baseline", "stretch"]],
- Literal["start", "center", "end", "baseline", "stretch"],
+ Breakpoints[
+ str, Literal["baseline", "center", "end", "start", "stretch"]
+ ],
+ Literal["baseline", "center", "end", "start", "stretch"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Literal["baseline", "center", "end", "start", "stretch"],
+ ],
+ Literal["baseline", "center", "end", "start", "stretch"],
+ ]
+ ],
]
] = None,
style: Optional[Style] = None,
@@ -127,52 +129,22 @@ class DataListItem(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DataListItem":
"""Create a new component instance.
@@ -181,6 +153,7 @@ class DataListItem(RadixThemesComponent):
Args:
*children: Child components.
+ align: The alignment of the data list item within its container.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -200,68 +173,74 @@ class DataListLabel(RadixThemesComponent):
def create( # type: ignore
cls,
*children,
- width: Optional[Union[Var[str], str]] = None,
- min_width: Optional[Union[Var[str], str]] = None,
- max_width: Optional[Union[Var[str], str]] = None,
+ width: Optional[
+ Union[Breakpoints[str, str], Var[Union[Breakpoints[str, str], str]], str]
+ ] = None,
+ min_width: Optional[
+ Union[Breakpoints[str, str], Var[Union[Breakpoints[str, str], str]], str]
+ ] = None,
+ max_width: Optional[
+ Union[Breakpoints[str, str], Var[Union[Breakpoints[str, str], str]], str]
+ ] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
@@ -271,52 +250,22 @@ class DataListLabel(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DataListLabel":
"""Create a new component instance.
@@ -325,6 +274,10 @@ class DataListLabel(RadixThemesComponent):
Args:
*children: Child components.
+ width: The width of the component
+ min_width: The minimum width of the component
+ max_width: The maximum width of the component
+ color_scheme: The color scheme for the DataList component.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -350,52 +303,22 @@ class DataListValue(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DataListValue":
"""Create a new component instance.
diff --git a/reflex/components/radix/themes/components/dialog.py b/reflex/components/radix/themes/components/dialog.py
index 1f25efd1b..e8da506ed 100644
--- a/reflex/components/radix/themes/components/dialog.py
+++ b/reflex/components/radix/themes/components/dialog.py
@@ -1,11 +1,12 @@
"""Interactive components provided by @radix-ui/themes."""
-from typing import Any, Dict, Literal
+from typing import Literal
-from reflex import el
from reflex.components.component import ComponentNamespace
-from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.components.el import elements
+from reflex.event import EventHandler, empty_event, identity_event
+from reflex.vars.base import Var
from ..base import (
RadixThemesComponent,
@@ -21,16 +22,8 @@ class DialogRoot(RadixThemesComponent):
# The controlled open state of the dialog.
open: Var[bool]
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
-
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_OPEN_CHANGE: lambda e0: [e0],
- }
+ # Fired when the open state changes.
+ on_open_change: EventHandler[identity_event(bool)]
class DialogTrigger(RadixThemesTriggerComponent):
@@ -45,28 +38,28 @@ class DialogTitle(RadixThemesComponent):
tag = "Dialog.Title"
-class DialogContent(el.Div, RadixThemesComponent):
+class DialogContent(elements.Div, RadixThemesComponent):
"""Content component to display inside a Dialog modal."""
tag = "Dialog.Content"
# DialogContent size "1" - "4"
- size: Var[Literal["1", "2", "3", "4"]]
+ size: Var[Responsive[Literal["1", "2", "3", "4"]]]
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
+ # Fired when the dialog is opened.
+ on_open_auto_focus: EventHandler[empty_event]
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_OPEN_AUTO_FOCUS: lambda e0: [e0],
- EventTriggers.ON_CLOSE_AUTO_FOCUS: lambda e0: [e0],
- EventTriggers.ON_ESCAPE_KEY_DOWN: lambda e0: [e0],
- EventTriggers.ON_POINTER_DOWN_OUTSIDE: lambda e0: [e0],
- EventTriggers.ON_INTERACT_OUTSIDE: lambda e0: [e0],
- }
+ # Fired when the dialog is closed.
+ on_close_auto_focus: EventHandler[empty_event]
+
+ # Fired when the escape key is pressed.
+ on_escape_key_down: EventHandler[empty_event]
+
+ # Fired when the pointer is down outside the dialog.
+ on_pointer_down_outside: EventHandler[empty_event]
+
+ # Fired when the pointer interacts outside the dialog.
+ on_interact_outside: EventHandler[empty_event]
class DialogDescription(RadixThemesComponent):
diff --git a/reflex/components/radix/themes/components/dialog.pyi b/reflex/components/radix/themes/components/dialog.pyi
index f3d158418..a277fc775 100644
--- a/reflex/components/radix/themes/components/dialog.pyi
+++ b/reflex/components/radix/themes/components/dialog.pyi
@@ -1,21 +1,20 @@
"""Stub file for reflex/components/radix/themes/components/dialog.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Any, Dict, Literal
-from reflex import el
+
from reflex.components.component import ComponentNamespace
-from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.components.el import elements
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
+
from ..base import RadixThemesComponent, RadixThemesTriggerComponent
class DialogRoot(RadixThemesComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
@@ -28,55 +27,23 @@ class DialogRoot(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_open_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_open_change: Optional[EventType[bool]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DialogRoot":
"""Create a new component instance.
@@ -86,6 +53,7 @@ class DialogRoot(RadixThemesComponent):
Args:
*children: Child components.
open: The controlled open state of the dialog.
+ on_open_change: Fired when the open state changes.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -111,52 +79,22 @@ class DialogTrigger(RadixThemesTriggerComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DialogTrigger":
"""Create a new RadixThemesTriggerComponent instance.
@@ -181,52 +119,22 @@ class DialogTitle(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DialogTitle":
"""Create a new component instance.
@@ -248,123 +156,75 @@ class DialogTitle(RadixThemesComponent):
"""
...
-class DialogContent(el.Div, RadixThemesComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
+class DialogContent(elements.Div, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
cls,
*children,
size: Optional[
- Union[Var[Literal["1", "2", "3", "4"]], Literal["1", "2", "3", "4"]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3", "4"]],
+ Literal["1", "2", "3", "4"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3", "4"]],
+ Literal["1", "2", "3", "4"],
+ ]
+ ],
+ ]
] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_close_auto_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_escape_key_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_interact_outside: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_open_auto_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_pointer_down_outside: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_close_auto_focus: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_escape_key_down: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_interact_outside: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_open_auto_focus: Optional[EventType[[]]] = None,
+ on_pointer_down_outside: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DialogContent":
"""Create a new component instance.
@@ -374,6 +234,11 @@ class DialogContent(el.Div, RadixThemesComponent):
Args:
*children: Child components.
size: DialogContent size "1" - "4"
+ on_open_auto_focus: Fired when the dialog is opened.
+ on_close_auto_focus: Fired when the dialog is closed.
+ on_escape_key_down: Fired when the escape key is pressed.
+ on_pointer_down_outside: Fired when the pointer is down outside the dialog.
+ on_interact_outside: Fired when the pointer interacts outside the dialog.
access_key: Provides a hint for generating a keyboard shortcut for the current element.
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
content_editable: Indicates whether the element's content is editable.
@@ -415,52 +280,22 @@ class DialogDescription(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DialogDescription":
"""Create a new component instance.
@@ -494,52 +329,22 @@ class DialogClose(RadixThemesTriggerComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DialogClose":
"""Create a new RadixThemesTriggerComponent instance.
@@ -570,55 +375,23 @@ class Dialog(ComponentNamespace):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_open_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_open_change: Optional[EventType[bool]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DialogRoot":
"""Create a new component instance.
@@ -628,6 +401,7 @@ class Dialog(ComponentNamespace):
Args:
*children: Child components.
open: The controlled open state of the dialog.
+ on_open_change: Fired when the open state changes.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
diff --git a/reflex/components/radix/themes/components/dropdown_menu.py b/reflex/components/radix/themes/components/dropdown_menu.py
index 350f15eba..885e8df35 100644
--- a/reflex/components/radix/themes/components/dropdown_menu.py
+++ b/reflex/components/radix/themes/components/dropdown_menu.py
@@ -1,9 +1,11 @@
"""Interactive components provided by @radix-ui/themes."""
-from typing import Any, Dict, List, Literal, Union
+
+from typing import Dict, List, Literal, Union
from reflex.components.component import ComponentNamespace
-from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.event import EventHandler, empty_event, identity_event
+from reflex.vars.base import Var
from ..base import (
LiteralAccentColor,
@@ -47,16 +49,8 @@ class DropdownMenuRoot(RadixThemesComponent):
_invalid_children: List[str] = ["DropdownMenuItem"]
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
-
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_OPEN_CHANGE: lambda e0: [e0],
- }
+ # Fired when the open state changes.
+ on_open_change: EventHandler[identity_event(bool)]
class DropdownMenuTrigger(RadixThemesTriggerComponent):
@@ -78,7 +72,7 @@ class DropdownMenuContent(RadixThemesComponent):
tag = "DropdownMenu.Content"
# Dropdown Menu Content size "1" - "2"
- size: Var[LiteralSizeType]
+ size: Var[Responsive[LiteralSizeType]]
# Variant of Dropdown Menu Content: "solid" | "soft"
variant: Var[LiteralVariantType]
@@ -125,20 +119,20 @@ class DropdownMenuContent(RadixThemesComponent):
# Whether to hide the content when the trigger becomes fully occluded. Defaults to False.
hide_when_detached: Var[bool]
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
+ # Fired when the dialog is closed.
+ on_close_auto_focus: EventHandler[empty_event]
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_CLOSE_AUTO_FOCUS: lambda e0: [e0],
- EventTriggers.ON_ESCAPE_KEY_DOWN: lambda e0: [e0],
- EventTriggers.ON_POINTER_DOWN_OUTSIDE: lambda e0: [e0],
- EventTriggers.ON_FOCUS_OUTSIDE: lambda e0: [e0],
- EventTriggers.ON_INTERACT_OUTSIDE: lambda e0: [e0],
- }
+ # Fired when the escape key is pressed.
+ on_escape_key_down: EventHandler[empty_event]
+
+ # Fired when the pointer is down outside the dialog.
+ on_pointer_down_outside: EventHandler[empty_event]
+
+ # Fired when focus moves outside the dialog.
+ on_focus_outside: EventHandler[empty_event]
+
+ # Fired when the pointer interacts outside the dialog.
+ on_interact_outside: EventHandler[empty_event]
class DropdownMenuSubTrigger(RadixThemesTriggerComponent):
@@ -169,16 +163,8 @@ class DropdownMenuSub(RadixThemesComponent):
# The open state of the submenu when it is initially rendered. Use when you do not need to control its open state.
default_open: Var[bool]
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
-
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_OPEN_CHANGE: lambda e0: [e0.target.value],
- }
+ # Fired when the open state changes.
+ on_open_change: EventHandler[identity_event(bool)]
class DropdownMenuSubContent(RadixThemesComponent):
@@ -218,19 +204,17 @@ class DropdownMenuSubContent(RadixThemesComponent):
_valid_parents: List[str] = ["DropdownMenuSub"]
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
+ # Fired when the escape key is pressed.
+ on_escape_key_down: EventHandler[empty_event]
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_ESCAPE_KEY_DOWN: lambda e0: [e0],
- EventTriggers.ON_POINTER_DOWN_OUTSIDE: lambda e0: [e0],
- EventTriggers.ON_FOCUS_OUTSIDE: lambda e0: [e0],
- EventTriggers.ON_INTERACT_OUTSIDE: lambda e0: [e0],
- }
+ # Fired when the pointer is down outside the dialog.
+ on_pointer_down_outside: EventHandler[empty_event]
+
+ # Fired when focus moves outside the dialog.
+ on_focus_outside: EventHandler[empty_event]
+
+ # Fired when the pointer interacts outside the dialog.
+ on_interact_outside: EventHandler[empty_event]
class DropdownMenuItem(RadixThemesComponent):
@@ -255,16 +239,8 @@ class DropdownMenuItem(RadixThemesComponent):
_valid_parents: List[str] = ["DropdownMenuContent", "DropdownMenuSubContent"]
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
-
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_SELECT: lambda e0: [e0.target.value],
- }
+ # Fired when the item is selected.
+ on_select: EventHandler[empty_event]
class DropdownMenuSeparator(RadixThemesComponent):
diff --git a/reflex/components/radix/themes/components/dropdown_menu.pyi b/reflex/components/radix/themes/components/dropdown_menu.pyi
index a8fad6d86..ccb2ef347 100644
--- a/reflex/components/radix/themes/components/dropdown_menu.pyi
+++ b/reflex/components/radix/themes/components/dropdown_menu.pyi
@@ -1,17 +1,17 @@
"""Stub file for reflex/components/radix/themes/components/dropdown_menu.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Any, Dict, List, Literal, Union
+
from reflex.components.component import ComponentNamespace
-from reflex.constants import EventTriggers
-from reflex.vars import Var
-from ..base import LiteralAccentColor, RadixThemesComponent, RadixThemesTriggerComponent
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent, RadixThemesTriggerComponent
LiteralDirType = Literal["ltr", "rtl"]
LiteralSizeType = Literal["1", "2"]
@@ -21,7 +21,6 @@ LiteralAlignType = Literal["start", "center", "end"]
LiteralStickyType = Literal["partial", "always"]
class DropdownMenuRoot(RadixThemesComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
@@ -30,62 +29,30 @@ class DropdownMenuRoot(RadixThemesComponent):
default_open: Optional[Union[Var[bool], bool]] = None,
open: Optional[Union[Var[bool], bool]] = None,
modal: Optional[Union[Var[bool], bool]] = None,
- dir: Optional[Union[Var[Literal["ltr", "rtl"]], Literal["ltr", "rtl"]]] = None,
+ dir: Optional[Union[Literal["ltr", "rtl"], Var[Literal["ltr", "rtl"]]]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_open_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_open_change: Optional[EventType[bool]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DropdownMenuRoot":
"""Create a new component instance.
@@ -98,6 +65,7 @@ class DropdownMenuRoot(RadixThemesComponent):
open: The controlled open state of the dropdown menu. Must be used in conjunction with onOpenChange.
modal: The modality of the dropdown menu. When set to true, interaction with outside elements will be disabled and only menu content will be visible to screen readers. Defaults to True.
dir: The reading direction of submenus when applicable. If omitted, inherits globally from DirectionProvider or assumes LTR (left-to-right) reading mode.
+ on_open_change: Fired when the open state changes.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -124,52 +92,22 @@ class DropdownMenuTrigger(RadixThemesTriggerComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DropdownMenuTrigger":
"""Create a new RadixThemesTriggerComponent instance.
@@ -183,75 +121,80 @@ class DropdownMenuTrigger(RadixThemesTriggerComponent):
...
class DropdownMenuContent(RadixThemesComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- size: Optional[Union[Var[Literal["1", "2"]], Literal["1", "2"]]] = None,
+ size: Optional[
+ Union[
+ Breakpoints[str, Literal["1", "2"]],
+ Literal["1", "2"],
+ Var[Union[Breakpoints[str, Literal["1", "2"]], Literal["1", "2"]]],
+ ]
+ ] = None,
variant: Optional[
- Union[Var[Literal["solid", "soft"]], Literal["solid", "soft"]]
+ Union[Literal["soft", "solid"], Var[Literal["soft", "solid"]]]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
@@ -261,30 +204,30 @@ class DropdownMenuContent(RadixThemesComponent):
force_mount: Optional[Union[Var[bool], bool]] = None,
side: Optional[
Union[
- Var[Literal["top", "right", "bottom", "left"]],
- Literal["top", "right", "bottom", "left"],
+ Literal["bottom", "left", "right", "top"],
+ Var[Literal["bottom", "left", "right", "top"]],
]
] = None,
- side_offset: Optional[Union[Var[Union[float, int]], Union[float, int]]] = None,
+ side_offset: Optional[Union[Var[Union[float, int]], float, int]] = None,
align: Optional[
Union[
- Var[Literal["start", "center", "end"]],
- Literal["start", "center", "end"],
+ Literal["center", "end", "start"],
+ Var[Literal["center", "end", "start"]],
]
] = None,
- align_offset: Optional[Union[Var[Union[float, int]], Union[float, int]]] = None,
+ align_offset: Optional[Union[Var[Union[float, int]], float, int]] = None,
avoid_collisions: Optional[Union[Var[bool], bool]] = None,
collision_padding: Optional[
Union[
- Var[Union[float, int, Dict[str, Union[float, int]]]],
- Union[float, int, Dict[str, Union[float, int]]],
+ Dict[str, Union[float, int]],
+ Var[Union[Dict[str, Union[float, int]], float, int]],
+ float,
+ int,
]
] = None,
- arrow_padding: Optional[
- Union[Var[Union[float, int]], Union[float, int]]
- ] = None,
+ arrow_padding: Optional[Union[Var[Union[float, int]], float, int]] = None,
sticky: Optional[
- Union[Var[Literal["partial", "always"]], Literal["partial", "always"]]
+ Union[Literal["always", "partial"], Var[Literal["always", "partial"]]]
] = None,
hide_when_detached: Optional[Union[Var[bool], bool]] = None,
style: Optional[Style] = None,
@@ -293,67 +236,27 @@ class DropdownMenuContent(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_close_auto_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_escape_key_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus_outside: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_interact_outside: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_pointer_down_outside: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_close_auto_focus: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_escape_key_down: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_focus_outside: Optional[EventType[[]]] = None,
+ on_interact_outside: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_pointer_down_outside: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DropdownMenuContent":
"""Create a new component instance.
@@ -378,6 +281,11 @@ class DropdownMenuContent(RadixThemesComponent):
arrow_padding: The padding between the arrow and the edges of the content. If your content has border-radius, this will prevent it from overflowing the corners. Defaults to 0.
sticky: The sticky behavior on the align axis. "partial" will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst "always" will keep the content in the boundary regardless. Defaults to "partial".
hide_when_detached: Whether to hide the content when the trigger becomes fully occluded. Defaults to False.
+ on_close_auto_focus: Fired when the dialog is closed.
+ on_escape_key_down: Fired when the escape key is pressed.
+ on_pointer_down_outside: Fired when the pointer is down outside the dialog.
+ on_focus_outside: Fired when focus moves outside the dialog.
+ on_interact_outside: Fired when the pointer interacts outside the dialog.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -406,52 +314,22 @@ class DropdownMenuSubTrigger(RadixThemesTriggerComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DropdownMenuSubTrigger":
"""Create a new RadixThemesTriggerComponent instance.
@@ -465,7 +343,6 @@ class DropdownMenuSubTrigger(RadixThemesTriggerComponent):
...
class DropdownMenuSub(RadixThemesComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
@@ -479,55 +356,23 @@ class DropdownMenuSub(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_open_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_open_change: Optional[EventType[bool]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DropdownMenuSub":
"""Create a new component instance.
@@ -538,6 +383,7 @@ class DropdownMenuSub(RadixThemesComponent):
*children: Child components.
open: The controlled open state of the submenu. Must be used in conjunction with `on_open_change`.
default_open: The open state of the submenu when it is initially rendered. Use when you do not need to control its open state.
+ on_open_change: Fired when the open state changes.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -552,7 +398,6 @@ class DropdownMenuSub(RadixThemesComponent):
...
class DropdownMenuSubContent(RadixThemesComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
@@ -561,20 +406,20 @@ class DropdownMenuSubContent(RadixThemesComponent):
as_child: Optional[Union[Var[bool], bool]] = None,
loop: Optional[Union[Var[bool], bool]] = None,
force_mount: Optional[Union[Var[bool], bool]] = None,
- side_offset: Optional[Union[Var[Union[float, int]], Union[float, int]]] = None,
- align_offset: Optional[Union[Var[Union[float, int]], Union[float, int]]] = None,
+ side_offset: Optional[Union[Var[Union[float, int]], float, int]] = None,
+ align_offset: Optional[Union[Var[Union[float, int]], float, int]] = None,
avoid_collisions: Optional[Union[Var[bool], bool]] = None,
collision_padding: Optional[
Union[
- Var[Union[float, int, Dict[str, Union[float, int]]]],
- Union[float, int, Dict[str, Union[float, int]]],
+ Dict[str, Union[float, int]],
+ Var[Union[Dict[str, Union[float, int]], float, int]],
+ float,
+ int,
]
] = None,
- arrow_padding: Optional[
- Union[Var[Union[float, int]], Union[float, int]]
- ] = None,
+ arrow_padding: Optional[Union[Var[Union[float, int]], float, int]] = None,
sticky: Optional[
- Union[Var[Literal["partial", "always"]], Literal["partial", "always"]]
+ Union[Literal["always", "partial"], Var[Literal["always", "partial"]]]
] = None,
hide_when_detached: Optional[Union[Var[bool], bool]] = None,
style: Optional[Style] = None,
@@ -583,64 +428,26 @@ class DropdownMenuSubContent(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_escape_key_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus_outside: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_interact_outside: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_pointer_down_outside: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_escape_key_down: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_focus_outside: Optional[EventType[[]]] = None,
+ on_interact_outside: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_pointer_down_outside: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DropdownMenuSubContent":
"""Create a new component instance.
@@ -659,6 +466,10 @@ class DropdownMenuSubContent(RadixThemesComponent):
arrow_padding: The padding between the arrow and the edges of the content. If your content has border-radius, this will prevent it from overflowing the corners. Defaults to 0.
sticky: The sticky behavior on the align axis. "partial" will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst "always" will keep the content in the boundary regardless. Defaults to "partial".
hide_when_detached: Whether to hide the content when the trigger becomes fully occluded. Defaults to False.
+ on_escape_key_down: Fired when the escape key is pressed.
+ on_pointer_down_outside: Fired when the pointer is down outside the dialog.
+ on_focus_outside: Fired when focus moves outside the dialog.
+ on_interact_outside: Fired when the pointer interacts outside the dialog.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -673,7 +484,6 @@ class DropdownMenuSubContent(RadixThemesComponent):
...
class DropdownMenuItem(RadixThemesComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
@@ -681,63 +491,63 @@ class DropdownMenuItem(RadixThemesComponent):
*children,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
@@ -751,55 +561,23 @@ class DropdownMenuItem(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_select: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_select: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DropdownMenuItem":
"""Create a new component instance.
@@ -813,6 +591,7 @@ class DropdownMenuItem(RadixThemesComponent):
as_child: Change the default rendered element for the one passed as a child, merging their props and behavior. Defaults to False.
disabled: When true, prevents the user from interacting with the item.
text_value: Optional text used for typeahead purposes. By default the typeahead behavior will use the .textContent of the item. Use this when the content is complex, or you have non-textual content inside.
+ on_select: Fired when the item is selected.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -838,52 +617,22 @@ class DropdownMenuSeparator(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "DropdownMenuSeparator":
"""Create a new component instance.
diff --git a/reflex/components/radix/themes/components/hover_card.py b/reflex/components/radix/themes/components/hover_card.py
index 9b90f98ce..e76184795 100644
--- a/reflex/components/radix/themes/components/hover_card.py
+++ b/reflex/components/radix/themes/components/hover_card.py
@@ -1,10 +1,12 @@
"""Interactive components provided by @radix-ui/themes."""
-from typing import Any, Dict, Literal
-from reflex import el
+from typing import Literal
+
from reflex.components.component import ComponentNamespace
-from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.components.el import elements
+from reflex.event import EventHandler, identity_event
+from reflex.vars.base import Var
from ..base import (
RadixThemesComponent,
@@ -29,16 +31,8 @@ class HoverCardRoot(RadixThemesComponent):
# The duration from when the mouse leaves the trigger until the hover card closes.
close_delay: Var[int]
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
-
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_OPEN_CHANGE: lambda e0: [e0],
- }
+ # Fired when the open state changes.
+ on_open_change: EventHandler[identity_event(bool)]
class HoverCardTrigger(RadixThemesTriggerComponent):
@@ -47,13 +41,13 @@ class HoverCardTrigger(RadixThemesTriggerComponent):
tag = "HoverCard.Trigger"
-class HoverCardContent(el.Div, RadixThemesComponent):
+class HoverCardContent(elements.Div, RadixThemesComponent):
"""Contains the content of the open hover card."""
tag = "HoverCard.Content"
# The preferred side of the trigger to render against when open. Will be reversed when collisions occur and avoidCollisions is enabled.
- side: Var[Literal["top", "right", "bottom", "left"]]
+ side: Var[Responsive[Literal["top", "right", "bottom", "left"]]]
# The distance in pixels from the trigger.
side_offset: Var[int]
diff --git a/reflex/components/radix/themes/components/hover_card.pyi b/reflex/components/radix/themes/components/hover_card.pyi
index 697ef2cdc..50c646971 100644
--- a/reflex/components/radix/themes/components/hover_card.pyi
+++ b/reflex/components/radix/themes/components/hover_card.pyi
@@ -1,21 +1,20 @@
"""Stub file for reflex/components/radix/themes/components/hover_card.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Any, Dict, Literal
-from reflex import el
+
from reflex.components.component import ComponentNamespace
-from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.components.el import elements
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
+
from ..base import RadixThemesComponent, RadixThemesTriggerComponent
class HoverCardRoot(RadixThemesComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
@@ -31,55 +30,23 @@ class HoverCardRoot(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_open_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_open_change: Optional[EventType[bool]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "HoverCardRoot":
"""Create a new component instance.
@@ -92,6 +59,7 @@ class HoverCardRoot(RadixThemesComponent):
open: The controlled open state of the hover card. Must be used in conjunction with onOpenChange.
open_delay: The duration from when the mouse enters the trigger until the hover card opens.
close_delay: The duration from when the mouse leaves the trigger until the hover card closes.
+ on_open_change: Fired when the open state changes.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -117,52 +85,22 @@ class HoverCardTrigger(RadixThemesTriggerComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "HoverCardTrigger":
"""Create a new RadixThemesTriggerComponent instance.
@@ -175,7 +113,7 @@ class HoverCardTrigger(RadixThemesTriggerComponent):
"""
...
-class HoverCardContent(el.Div, RadixThemesComponent):
+class HoverCardContent(elements.Div, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
@@ -183,110 +121,70 @@ class HoverCardContent(el.Div, RadixThemesComponent):
*children,
side: Optional[
Union[
- Var[Literal["top", "right", "bottom", "left"]],
- Literal["top", "right", "bottom", "left"],
+ Breakpoints[str, Literal["bottom", "left", "right", "top"]],
+ Literal["bottom", "left", "right", "top"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["bottom", "left", "right", "top"]],
+ Literal["bottom", "left", "right", "top"],
+ ]
+ ],
]
] = None,
side_offset: Optional[Union[Var[int], int]] = None,
align: Optional[
Union[
- Var[Literal["start", "center", "end"]],
- Literal["start", "center", "end"],
+ Literal["center", "end", "start"],
+ Var[Literal["center", "end", "start"]],
]
] = None,
avoid_collisions: Optional[Union[Var[bool], bool]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "HoverCardContent":
"""Create a new component instance.
@@ -346,55 +244,23 @@ class HoverCard(ComponentNamespace):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_open_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_open_change: Optional[EventType[bool]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "HoverCardRoot":
"""Create a new component instance.
@@ -407,6 +273,7 @@ class HoverCard(ComponentNamespace):
open: The controlled open state of the hover card. Must be used in conjunction with onOpenChange.
open_delay: The duration from when the mouse enters the trigger until the hover card opens.
close_delay: The duration from when the mouse leaves the trigger until the hover card closes.
+ on_open_change: Fired when the open state changes.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
diff --git a/reflex/components/radix/themes/components/icon_button.py b/reflex/components/radix/themes/components/icon_button.py
index 452e37640..2a32afe3a 100644
--- a/reflex/components/radix/themes/components/icon_button.py
+++ b/reflex/components/radix/themes/components/icon_button.py
@@ -1,14 +1,16 @@
"""Interactive components provided by @radix-ui/themes."""
+
from __future__ import annotations
from typing import Literal
-from reflex import el
from reflex.components.component import Component
+from reflex.components.core.breakpoints import Responsive
from reflex.components.core.match import Match
+from reflex.components.el import elements
from reflex.components.lucide import Icon
from reflex.style import Style
-from reflex.vars import Var
+from reflex.vars.base import Var
from ..base import (
LiteralAccentColor,
@@ -21,7 +23,7 @@ from ..base import (
LiteralButtonSize = Literal["1", "2", "3", "4"]
-class IconButton(el.Button, RadixLoadingProp, RadixThemesComponent):
+class IconButton(elements.Button, RadixLoadingProp, RadixThemesComponent):
"""A button designed specifically for usage with a single icon."""
tag = "IconButton"
@@ -30,7 +32,7 @@ class IconButton(el.Button, RadixLoadingProp, RadixThemesComponent):
as_child: Var[bool]
# Button size "1" - "4"
- size: Var[LiteralButtonSize]
+ size: Var[Responsive[LiteralButtonSize]]
# Variant of button: "classic" | "solid" | "soft" | "surface" | "outline" | "ghost"
variant: Var[LiteralVariant]
diff --git a/reflex/components/radix/themes/components/icon_button.pyi b/reflex/components/radix/themes/components/icon_button.pyi
index 3e3657dbf..901c8d6ff 100644
--- a/reflex/components/radix/themes/components/icon_button.pyi
+++ b/reflex/components/radix/themes/components/icon_button.pyi
@@ -1,30 +1,24 @@
"""Stub file for reflex/components/radix/themes/components/icon_button.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.components.el import elements
+from reflex.event import EventType
from reflex.style import Style
-from typing import Literal
-from reflex import el
-from reflex.components.component import Component
-from reflex.components.core.match import Match
-from reflex.components.lucide import Icon
-from reflex.style import Style
-from reflex.vars import Var
+from reflex.vars.base import Var
+
from ..base import (
- LiteralAccentColor,
- LiteralRadius,
- LiteralVariant,
RadixLoadingProp,
RadixThemesComponent,
)
LiteralButtonSize = Literal["1", "2", "3", "4"]
-class IconButton(el.Button, RadixLoadingProp, RadixThemesComponent):
+class IconButton(elements.Button, RadixLoadingProp, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
@@ -32,148 +26,131 @@ class IconButton(el.Button, RadixLoadingProp, RadixThemesComponent):
*children,
as_child: Optional[Union[Var[bool], bool]] = None,
size: Optional[
- Union[Var[Literal["1", "2", "3", "4"]], Literal["1", "2", "3", "4"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3", "4"]],
+ Literal["1", "2", "3", "4"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3", "4"]],
+ Literal["1", "2", "3", "4"],
+ ]
+ ],
+ ]
] = None,
variant: Optional[
Union[
- Var[Literal["classic", "solid", "soft", "surface", "outline", "ghost"]],
- Literal["classic", "solid", "soft", "surface", "outline", "ghost"],
+ Literal["classic", "ghost", "outline", "soft", "solid", "surface"],
+ Var[Literal["classic", "ghost", "outline", "soft", "solid", "surface"]],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
radius: Optional[
Union[
- Var[Literal["none", "small", "medium", "large", "full"]],
- Literal["none", "small", "medium", "large", "full"],
+ Literal["full", "large", "medium", "none", "small"],
+ Var[Literal["full", "large", "medium", "none", "small"]],
]
] = None,
- auto_focus: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ auto_focus: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
disabled: Optional[Union[Var[bool], bool]] = None,
- form: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- form_action: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ form: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ form_action: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
form_enc_type: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- form_method: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ form_method: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
form_no_validate: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- form_target: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- name: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- type: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- value: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ form_target: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ name: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ type: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ value: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
loading: Optional[Union[Var[bool], bool]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
@@ -181,52 +158,22 @@ class IconButton(el.Button, RadixLoadingProp, RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "IconButton":
"""Create a IconButton component.
@@ -281,6 +228,7 @@ class IconButton(el.Button, RadixLoadingProp, RadixThemesComponent):
The IconButton component.
"""
...
+
def add_style(self): ...
icon_button = IconButton.create
diff --git a/reflex/components/radix/themes/components/inset.py b/reflex/components/radix/themes/components/inset.py
index fcdafc6a0..347b9f6b0 100644
--- a/reflex/components/radix/themes/components/inset.py
+++ b/reflex/components/radix/themes/components/inset.py
@@ -1,8 +1,10 @@
"""Interactive components provided by @radix-ui/themes."""
+
from typing import Literal, Union
-from reflex import el
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.components.el import elements
+from reflex.vars.base import Var
from ..base import (
RadixThemesComponent,
@@ -11,37 +13,37 @@ from ..base import (
LiteralButtonSize = Literal["1", "2", "3", "4"]
-class Inset(el.Div, RadixThemesComponent):
+class Inset(elements.Div, RadixThemesComponent):
"""Applies a negative margin to allow content to bleed into the surrounding container."""
tag = "Inset"
# The side
- side: Var[Literal["x", "y", "top", "bottom", "right", "left"]]
+ side: Var[Responsive[Literal["x", "y", "top", "bottom", "right", "left"]]]
# How to clip the element's content: "border-box" | "padding-box"
- clip: Var[Literal["border-box", "padding-box"]]
+ clip: Var[Responsive[Literal["border-box", "padding-box"]]]
# Padding
- p: Var[Union[int, str]]
+ p: Var[Responsive[Union[int, str]]]
# Padding on the x axis
- px: Var[Union[int, str]]
+ px: Var[Responsive[Union[int, str]]]
# Padding on the y axis
- py: Var[Union[int, str]]
+ py: Var[Responsive[Union[int, str]]]
# Padding on the top
- pt: Var[Union[int, str]]
+ pt: Var[Responsive[Union[int, str]]]
# Padding on the right
- pr: Var[Union[int, str]]
+ pr: Var[Responsive[Union[int, str]]]
# Padding on the bottom
- pb: Var[Union[int, str]]
+ pb: Var[Responsive[Union[int, str]]]
# Padding on the left
- pl: Var[Union[int, str]]
+ pl: Var[Responsive[Union[int, str]]]
inset = Inset.create
diff --git a/reflex/components/radix/themes/components/inset.pyi b/reflex/components/radix/themes/components/inset.pyi
index 23f212d09..d6b0cce04 100644
--- a/reflex/components/radix/themes/components/inset.pyi
+++ b/reflex/components/radix/themes/components/inset.pyi
@@ -1,20 +1,21 @@
"""Stub file for reflex/components/radix/themes/components/inset.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.components.el import elements
+from reflex.event import EventType
from reflex.style import Style
-from typing import Literal, Union
-from reflex import el
-from reflex.vars import Var
+from reflex.vars.base import Var
+
from ..base import RadixThemesComponent
LiteralButtonSize = Literal["1", "2", "3", "4"]
-class Inset(el.Div, RadixThemesComponent):
+class Inset(elements.Div, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
@@ -22,115 +23,132 @@ class Inset(el.Div, RadixThemesComponent):
*children,
side: Optional[
Union[
- Var[Literal["x", "y", "top", "bottom", "right", "left"]],
- Literal["x", "y", "top", "bottom", "right", "left"],
+ Breakpoints[str, Literal["bottom", "left", "right", "top", "x", "y"]],
+ Literal["bottom", "left", "right", "top", "x", "y"],
+ Var[
+ Union[
+ Breakpoints[
+ str, Literal["bottom", "left", "right", "top", "x", "y"]
+ ],
+ Literal["bottom", "left", "right", "top", "x", "y"],
+ ]
+ ],
]
] = None,
clip: Optional[
Union[
- Var[Literal["border-box", "padding-box"]],
+ Breakpoints[str, Literal["border-box", "padding-box"]],
Literal["border-box", "padding-box"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["border-box", "padding-box"]],
+ Literal["border-box", "padding-box"],
+ ]
+ ],
]
] = None,
- p: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- px: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- py: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- pt: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- pr: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- pb: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- pl: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ p: Optional[
+ Union[
+ Breakpoints[str, Union[int, str]],
+ Var[Union[Breakpoints[str, Union[int, str]], int, str]],
+ int,
+ str,
+ ]
] = None,
+ px: Optional[
+ Union[
+ Breakpoints[str, Union[int, str]],
+ Var[Union[Breakpoints[str, Union[int, str]], int, str]],
+ int,
+ str,
+ ]
+ ] = None,
+ py: Optional[
+ Union[
+ Breakpoints[str, Union[int, str]],
+ Var[Union[Breakpoints[str, Union[int, str]], int, str]],
+ int,
+ str,
+ ]
+ ] = None,
+ pt: Optional[
+ Union[
+ Breakpoints[str, Union[int, str]],
+ Var[Union[Breakpoints[str, Union[int, str]], int, str]],
+ int,
+ str,
+ ]
+ ] = None,
+ pr: Optional[
+ Union[
+ Breakpoints[str, Union[int, str]],
+ Var[Union[Breakpoints[str, Union[int, str]], int, str]],
+ int,
+ str,
+ ]
+ ] = None,
+ pb: Optional[
+ Union[
+ Breakpoints[str, Union[int, str]],
+ Var[Union[Breakpoints[str, Union[int, str]], int, str]],
+ int,
+ str,
+ ]
+ ] = None,
+ pl: Optional[
+ Union[
+ Breakpoints[str, Union[int, str]],
+ Var[Union[Breakpoints[str, Union[int, str]], int, str]],
+ int,
+ str,
+ ]
+ ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Inset":
"""Create a new component instance.
diff --git a/reflex/components/radix/themes/components/popover.py b/reflex/components/radix/themes/components/popover.py
index 08415ba56..2535a8a22 100644
--- a/reflex/components/radix/themes/components/popover.py
+++ b/reflex/components/radix/themes/components/popover.py
@@ -1,10 +1,12 @@
"""Interactive components provided by @radix-ui/themes."""
-from typing import Any, Dict, Literal
-from reflex import el
+from typing import Literal
+
from reflex.components.component import ComponentNamespace
-from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.components.el import elements
+from reflex.event import EventHandler, empty_event, identity_event
+from reflex.vars.base import Var
from ..base import (
RadixThemesComponent,
@@ -23,16 +25,8 @@ class PopoverRoot(RadixThemesComponent):
# The modality of the popover. When set to true, interaction with outside elements will be disabled and only popover content will be visible to screen readers.
modal: Var[bool]
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
-
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_OPEN_CHANGE: lambda e0: [e0],
- }
+ # Fired when the open state changes.
+ on_open_change: EventHandler[identity_event(bool)]
class PopoverTrigger(RadixThemesTriggerComponent):
@@ -41,13 +35,13 @@ class PopoverTrigger(RadixThemesTriggerComponent):
tag = "Popover.Trigger"
-class PopoverContent(el.Div, RadixThemesComponent):
+class PopoverContent(elements.Div, RadixThemesComponent):
"""Contains content to be rendered in the open popover."""
tag = "Popover.Content"
# Size of the button: "1" | "2" | "3" | "4"
- size: Var[Literal["1", "2", "3", "4"]]
+ size: Var[Responsive[Literal["1", "2", "3", "4"]]]
# The preferred side of the anchor to render against when open. Will be reversed when collisions occur and avoidCollisions is enabled.
side: Var[Literal["top", "right", "bottom", "left"]]
@@ -64,21 +58,23 @@ class PopoverContent(el.Div, RadixThemesComponent):
# When true, overrides the side andalign preferences to prevent collisions with boundary edges.
avoid_collisions: Var[bool]
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
+ # Fired when the dialog is opened.
+ on_open_auto_focus: EventHandler[empty_event]
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_OPEN_AUTO_FOCUS: lambda e0: [e0],
- EventTriggers.ON_CLOSE_AUTO_FOCUS: lambda e0: [e0],
- EventTriggers.ON_ESCAPE_KEY_DOWN: lambda e0: [e0],
- EventTriggers.ON_POINTER_DOWN_OUTSIDE: lambda e0: [e0],
- EventTriggers.ON_FOCUS_OUTSIDE: lambda e0: [e0],
- EventTriggers.ON_INTERACT_OUTSIDE: lambda e0: [e0],
- }
+ # Fired when the dialog is closed.
+ on_close_auto_focus: EventHandler[empty_event]
+
+ # Fired when the escape key is pressed.
+ on_escape_key_down: EventHandler[empty_event]
+
+ # Fired when the pointer is down outside the dialog.
+ on_pointer_down_outside: EventHandler[empty_event]
+
+ # Fired when focus moves outside the dialog.
+ on_focus_outside: EventHandler[empty_event]
+
+ # Fired when the pointer interacts outside the dialog.
+ on_interact_outside: EventHandler[empty_event]
class PopoverClose(RadixThemesTriggerComponent):
diff --git a/reflex/components/radix/themes/components/popover.pyi b/reflex/components/radix/themes/components/popover.pyi
index 04d705051..35f6854f6 100644
--- a/reflex/components/radix/themes/components/popover.pyi
+++ b/reflex/components/radix/themes/components/popover.pyi
@@ -1,21 +1,20 @@
"""Stub file for reflex/components/radix/themes/components/popover.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Any, Dict, Literal
-from reflex import el
+
from reflex.components.component import ComponentNamespace
-from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.components.el import elements
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
+
from ..base import RadixThemesComponent, RadixThemesTriggerComponent
class PopoverRoot(RadixThemesComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
@@ -29,55 +28,23 @@ class PopoverRoot(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_open_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_open_change: Optional[EventType[bool]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "PopoverRoot":
"""Create a new component instance.
@@ -88,6 +55,7 @@ class PopoverRoot(RadixThemesComponent):
*children: Child components.
open: The controlled open state of the popover.
modal: The modality of the popover. When set to true, interaction with outside elements will be disabled and only popover content will be visible to screen readers.
+ on_open_change: Fired when the open state changes.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -113,52 +81,22 @@ class PopoverTrigger(RadixThemesTriggerComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "PopoverTrigger":
"""Create a new RadixThemesTriggerComponent instance.
@@ -171,141 +109,91 @@ class PopoverTrigger(RadixThemesTriggerComponent):
"""
...
-class PopoverContent(el.Div, RadixThemesComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
+class PopoverContent(elements.Div, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
cls,
*children,
size: Optional[
- Union[Var[Literal["1", "2", "3", "4"]], Literal["1", "2", "3", "4"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3", "4"]],
+ Literal["1", "2", "3", "4"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3", "4"]],
+ Literal["1", "2", "3", "4"],
+ ]
+ ],
+ ]
] = None,
side: Optional[
Union[
- Var[Literal["top", "right", "bottom", "left"]],
- Literal["top", "right", "bottom", "left"],
+ Literal["bottom", "left", "right", "top"],
+ Var[Literal["bottom", "left", "right", "top"]],
]
] = None,
side_offset: Optional[Union[Var[int], int]] = None,
align: Optional[
Union[
- Var[Literal["start", "center", "end"]],
- Literal["start", "center", "end"],
+ Literal["center", "end", "start"],
+ Var[Literal["center", "end", "start"]],
]
] = None,
align_offset: Optional[Union[Var[int], int]] = None,
avoid_collisions: Optional[Union[Var[bool], bool]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_close_auto_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_escape_key_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus_outside: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_interact_outside: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_open_auto_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_pointer_down_outside: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_close_auto_focus: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_escape_key_down: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_focus_outside: Optional[EventType[[]]] = None,
+ on_interact_outside: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_open_auto_focus: Optional[EventType[[]]] = None,
+ on_pointer_down_outside: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "PopoverContent":
"""Create a new component instance.
@@ -320,6 +208,12 @@ class PopoverContent(el.Div, RadixThemesComponent):
align: The preferred alignment against the anchor. May change when collisions occur.
align_offset: The vertical distance in pixels from the anchor.
avoid_collisions: When true, overrides the side andalign preferences to prevent collisions with boundary edges.
+ on_open_auto_focus: Fired when the dialog is opened.
+ on_close_auto_focus: Fired when the dialog is closed.
+ on_escape_key_down: Fired when the escape key is pressed.
+ on_pointer_down_outside: Fired when the pointer is down outside the dialog.
+ on_focus_outside: Fired when focus moves outside the dialog.
+ on_interact_outside: Fired when the pointer interacts outside the dialog.
access_key: Provides a hint for generating a keyboard shortcut for the current element.
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
content_editable: Indicates whether the element's content is editable.
@@ -361,52 +255,22 @@ class PopoverClose(RadixThemesTriggerComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "PopoverClose":
"""Create a new RadixThemesTriggerComponent instance.
diff --git a/reflex/components/radix/themes/components/progress.py b/reflex/components/radix/themes/components/progress.py
index bcd64edb8..e9fe168c6 100644
--- a/reflex/components/radix/themes/components/progress.py
+++ b/reflex/components/radix/themes/components/progress.py
@@ -3,7 +3,9 @@
from typing import Literal
from reflex.components.component import Component
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.style import Style
+from reflex.vars.base import Var
from ..base import LiteralAccentColor, RadixThemesComponent
@@ -20,7 +22,7 @@ class Progress(RadixThemesComponent):
max: Var[int]
# The size of the progress bar: "1" | "2" | "3"
- size: Var[Literal["1", "2", "3"]]
+ size: Var[Responsive[Literal["1", "2", "3"]]]
# The variant of the progress bar: "classic" | "surface" | "soft"
variant: Var[Literal["classic", "surface", "soft"]]
@@ -37,6 +39,21 @@ class Progress(RadixThemesComponent):
# The duration of the progress bar animation. Once the duration times out, the progress bar will start an indeterminate animation.
duration: Var[str]
+ # The color of the progress bar fill animation.
+ fill_color: Var[str]
+
+ @staticmethod
+ def _color_selector(color: str) -> Style:
+ """Return a style object with the correct color and css selector.
+
+ Args:
+ color: Color of the fill part.
+
+ Returns:
+ Style: Style object with the correct css selector and color.
+ """
+ return Style({".rt-ProgressIndicator": {"background_color": color}})
+
@classmethod
def create(cls, *children, **props) -> Component:
"""Create a Progress component.
@@ -49,6 +66,12 @@ class Progress(RadixThemesComponent):
The Progress Component.
"""
props.setdefault("width", "100%")
+ if "fill_color" in props:
+ color = props.get("fill_color", "")
+ style = props.get("style", {})
+ style = style | cls._color_selector(color)
+ props["style"] = style
+
return super().create(*children, **props)
diff --git a/reflex/components/radix/themes/components/progress.pyi b/reflex/components/radix/themes/components/progress.pyi
index e72b83273..6470842f3 100644
--- a/reflex/components/radix/themes/components/progress.pyi
+++ b/reflex/components/radix/themes/components/progress.pyi
@@ -1,16 +1,16 @@
"""Stub file for reflex/components/radix/themes/components/progress.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.event import EventType
from reflex.style import Style
-from typing import Literal
-from reflex.components.component import Component
-from reflex.vars import Var
-from ..base import LiteralAccentColor, RadixThemesComponent
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
class Progress(RadixThemesComponent):
@overload
@@ -21,136 +21,115 @@ class Progress(RadixThemesComponent):
value: Optional[Union[Var[int], int]] = None,
max: Optional[Union[Var[int], int]] = None,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
variant: Optional[
Union[
- Var[Literal["classic", "surface", "soft"]],
- Literal["classic", "surface", "soft"],
+ Literal["classic", "soft", "surface"],
+ Var[Literal["classic", "soft", "surface"]],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
radius: Optional[
Union[
- Var[Literal["none", "small", "medium", "large", "full"]],
- Literal["none", "small", "medium", "large", "full"],
+ Literal["full", "large", "medium", "none", "small"],
+ Var[Literal["full", "large", "medium", "none", "small"]],
]
] = None,
duration: Optional[Union[Var[str], str]] = None,
+ fill_color: Optional[Union[Var[str], str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Progress":
"""Create a Progress component.
@@ -164,6 +143,7 @@ class Progress(RadixThemesComponent):
high_contrast: Whether to render the progress bar with higher contrast color against background
radius: Override theme radius for progress bar: "none" | "small" | "medium" | "large" | "full"
duration: The duration of the progress bar animation. Once the duration times out, the progress bar will start an indeterminate animation.
+ fill_color: The color of the progress bar fill animation.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
diff --git a/reflex/components/radix/themes/components/radio.py b/reflex/components/radix/themes/components/radio.py
index f8939b292..fd24bb6b5 100644
--- a/reflex/components/radix/themes/components/radio.py
+++ b/reflex/components/radix/themes/components/radio.py
@@ -2,7 +2,8 @@
from typing import Literal
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.vars.base import Var
from ..base import LiteralAccentColor, RadixThemesComponent
@@ -13,7 +14,7 @@ class Radio(RadixThemesComponent):
tag = "Radio"
# The size of the radio: "1" | "2" | "3"
- size: Var[Literal["1", "2", "3"]]
+ size: Var[Responsive[Literal["1", "2", "3"]]]
# Variant of button: "classic" | "surface" | "soft"
variant: Var[Literal["classic", "surface", "soft"]]
diff --git a/reflex/components/radix/themes/components/radio.pyi b/reflex/components/radix/themes/components/radio.pyi
index 72e5e90cb..f1a6b131a 100644
--- a/reflex/components/radix/themes/components/radio.pyi
+++ b/reflex/components/radix/themes/components/radio.pyi
@@ -1,15 +1,16 @@
"""Stub file for reflex/components/radix/themes/components/radio.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.event import EventType
from reflex.style import Style
-from typing import Literal
-from reflex.vars import Var
-from ..base import LiteralAccentColor, RadixThemesComponent
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
class Radio(RadixThemesComponent):
@overload
@@ -18,73 +19,81 @@ class Radio(RadixThemesComponent):
cls,
*children,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
variant: Optional[
Union[
- Var[Literal["classic", "surface", "soft"]],
- Literal["classic", "surface", "soft"],
+ Literal["classic", "soft", "surface"],
+ Var[Literal["classic", "soft", "surface"]],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
@@ -95,52 +104,22 @@ class Radio(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Radio":
"""Create a new component instance.
diff --git a/reflex/components/radix/themes/components/radio_cards.py b/reflex/components/radix/themes/components/radio_cards.py
index aed7f4d11..e0aa2a749 100644
--- a/reflex/components/radix/themes/components/radio_cards.py
+++ b/reflex/components/radix/themes/components/radio_cards.py
@@ -3,7 +3,9 @@
from types import SimpleNamespace
from typing import Literal, Union
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.event import EventHandler, identity_event
+from reflex.vars.base import Var
from ..base import LiteralAccentColor, RadixThemesComponent
@@ -13,8 +15,11 @@ class RadioCardsRoot(RadixThemesComponent):
tag = "RadioCards.Root"
+ # Change the default rendered element for the one passed as a child, merging their props and behavior.
+ as_child: Var[bool]
+
# The size of the checkbox cards: "1" | "2" | "3"
- size: Var[Literal["1", "2", "3"]]
+ size: Var[Responsive[Literal["1", "2", "3"]]]
# Variant of button: "classic" | "surface" | "soft"
variant: Var[Literal["classic", "surface"]]
@@ -26,10 +31,41 @@ class RadioCardsRoot(RadixThemesComponent):
high_contrast: Var[bool]
# The number of columns:
- columns: Var[Union[str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]]]
+ columns: Var[
+ Responsive[Union[str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]]]
+ ]
# The gap between the checkbox cards:
- gap: Var[Union[str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]]]
+ gap: Var[
+ Responsive[Union[str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]]]
+ ]
+
+ default_value: Var[str]
+
+ # The controlled value of the radio item to check. Should be used in conjunction with onValueChange.
+ value: Var[str]
+
+ # The name of the group. Submitted with its owning form as part of a name/value pair.
+ name: Var[str]
+
+ # When true, prevents the user from interacting with radio items.
+ disabled: Var[bool]
+
+ # When true, indicates that the user must check a radio item before the owning form can be submitted.
+ required: Var[bool]
+
+ # The orientation of the component.
+ orientation: Var[Literal["horizontal", "vertical", "undefined"]]
+
+ # The reading direction of the radio group. If omitted,
+ # inherits globally from DirectionProvider or assumes LTR (left-to-right) reading mode.
+ dir: Var[Literal["ltr", "rtl"]]
+
+ # When true, keyboard navigation will loop from last item to first, and vice versa.
+ loop: Var[bool]
+
+ # Event handler called when the value changes.
+ on_value_change: EventHandler[identity_event(str)]
class RadioCardsItem(RadixThemesComponent):
@@ -37,6 +73,18 @@ class RadioCardsItem(RadixThemesComponent):
tag = "RadioCards.Item"
+ # Change the default rendered element for the one passed as a child, merging their props and behavior.
+ as_child: Var[bool]
+
+ # The value given as data when submitted with a name.
+ value: Var[str]
+
+ # When true, prevents the user from interacting with the radio item.
+ disabled: Var[bool]
+
+ # When true, indicates that the user must check the radio item before the owning form can be submitted.
+ required: Var[bool]
+
class RadioCards(SimpleNamespace):
"""RadioCards components namespace."""
diff --git a/reflex/components/radix/themes/components/radio_cards.pyi b/reflex/components/radix/themes/components/radio_cards.pyi
index 2985476f3..ac6a645a9 100644
--- a/reflex/components/radix/themes/components/radio_cards.pyi
+++ b/reflex/components/radix/themes/components/radio_cards.pyi
@@ -1,16 +1,17 @@
"""Stub file for reflex/components/radix/themes/components/radio_cards.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
from types import SimpleNamespace
-from typing import Literal, Union
-from reflex.vars import Var
-from ..base import LiteralAccentColor, RadixThemesComponent
+from typing import Any, Dict, Literal, Optional, Union, overload
+
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
class RadioCardsRoot(RadixThemesComponent):
@overload
@@ -18,139 +19,166 @@ class RadioCardsRoot(RadixThemesComponent):
def create( # type: ignore
cls,
*children,
+ as_child: Optional[Union[Var[bool], bool]] = None,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
variant: Optional[
- Union[Var[Literal["classic", "surface"]], Literal["classic", "surface"]]
+ Union[Literal["classic", "surface"], Var[Literal["classic", "surface"]]]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
columns: Optional[
Union[
- Var[Union[str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]]],
- Union[str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[
+ str,
+ Union[Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"], str],
+ ],
+ Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Union[
+ Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ str,
+ ],
+ ],
+ Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ str,
+ ]
+ ],
+ str,
]
] = None,
gap: Optional[
Union[
- Var[Union[str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]]],
- Union[str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[
+ str,
+ Union[Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"], str],
+ ],
+ Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Union[
+ Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ str,
+ ],
+ ],
+ Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ str,
+ ]
+ ],
+ str,
]
] = None,
+ default_value: Optional[Union[Var[str], str]] = None,
+ value: Optional[Union[Var[str], str]] = None,
+ name: Optional[Union[Var[str], str]] = None,
+ disabled: Optional[Union[Var[bool], bool]] = None,
+ required: Optional[Union[Var[bool], bool]] = None,
+ orientation: Optional[
+ Union[
+ Literal["horizontal", "undefined", "vertical"],
+ Var[Literal["horizontal", "undefined", "vertical"]],
+ ]
+ ] = None,
+ dir: Optional[Union[Literal["ltr", "rtl"], Var[Literal["ltr", "rtl"]]]] = None,
+ loop: Optional[Union[Var[bool], bool]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ on_value_change: Optional[EventType[str]] = None,
+ **props,
) -> "RadioCardsRoot":
"""Create a new component instance.
@@ -159,12 +187,21 @@ class RadioCardsRoot(RadixThemesComponent):
Args:
*children: Child components.
+ as_child: Change the default rendered element for the one passed as a child, merging their props and behavior.
size: The size of the checkbox cards: "1" | "2" | "3"
variant: Variant of button: "classic" | "surface" | "soft"
color_scheme: Override theme color for button
high_contrast: Uses a higher contrast color for the component.
columns: The number of columns:
gap: The gap between the checkbox cards:
+ value: The controlled value of the radio item to check. Should be used in conjunction with onValueChange.
+ name: The name of the group. Submitted with its owning form as part of a name/value pair.
+ disabled: When true, prevents the user from interacting with radio items.
+ required: When true, indicates that the user must check a radio item before the owning form can be submitted.
+ orientation: The orientation of the component.
+ dir: The reading direction of the radio group. If omitted, inherits globally from DirectionProvider or assumes LTR (left-to-right) reading mode.
+ loop: When true, keyboard navigation will loop from last item to first, and vice versa.
+ on_value_change: Event handler called when the value changes.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -184,58 +221,32 @@ class RadioCardsItem(RadixThemesComponent):
def create( # type: ignore
cls,
*children,
+ as_child: Optional[Union[Var[bool], bool]] = None,
+ value: Optional[Union[Var[str], str]] = None,
+ disabled: Optional[Union[Var[bool], bool]] = None,
+ required: Optional[Union[Var[bool], bool]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "RadioCardsItem":
"""Create a new component instance.
@@ -244,6 +255,10 @@ class RadioCardsItem(RadixThemesComponent):
Args:
*children: Child components.
+ as_child: Change the default rendered element for the one passed as a child, merging their props and behavior.
+ value: The value given as data when submitted with a name.
+ disabled: When true, prevents the user from interacting with the radio item.
+ required: When true, indicates that the user must check the radio item before the owning form can be submitted.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
diff --git a/reflex/components/radix/themes/components/radio_group.py b/reflex/components/radix/themes/components/radio_group.py
index 223b04cfe..a55ca3a41 100644
--- a/reflex/components/radix/themes/components/radio_group.py
+++ b/reflex/components/radix/themes/components/radio_group.py
@@ -1,14 +1,18 @@
"""Interactive components provided by @radix-ui/themes."""
+
from __future__ import annotations
-from typing import Any, Dict, List, Literal, Optional, Union
+from typing import List, Literal, Optional, Union
import reflex as rx
from reflex.components.component import Component, ComponentNamespace
+from reflex.components.core.breakpoints import Responsive
from reflex.components.radix.themes.layout.flex import Flex
from reflex.components.radix.themes.typography.text import Text
-from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.event import EventHandler, identity_event
+from reflex.utils import types
+from reflex.vars.base import LiteralVar, Var
+from reflex.vars.sequence import StringVar
from ..base import (
LiteralAccentColor,
@@ -25,10 +29,10 @@ class RadioGroupRoot(RadixThemesComponent):
tag = "RadioGroup.Root"
# The size of the radio group: "1" | "2" | "3"
- size: Var[Literal["1", "2", "3"]]
+ size: Var[Responsive[Literal["1", "2", "3"]]] = LiteralVar.create("2")
# The variant of the radio group
- variant: Var[Literal["classic", "surface", "soft"]]
+ variant: Var[Literal["classic", "surface", "soft"]] = LiteralVar.create("classic")
# The color of the radio group
color_scheme: Var[LiteralAccentColor]
@@ -54,16 +58,8 @@ class RadioGroupRoot(RadixThemesComponent):
# Props to rename
_rename_props = {"onChange": "onValueChange"}
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
-
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_CHANGE: lambda e0: [e0],
- }
+ # Fired when the value of the radio group changes.
+ on_change: EventHandler[identity_event(str)]
class RadioGroupItem(RadixThemesComponent):
@@ -88,16 +84,16 @@ class HighLevelRadioGroup(RadixThemesComponent):
items: Var[List[str]]
# The direction of the radio group.
- direction: Var[LiteralFlexDirection]
+ direction: Var[LiteralFlexDirection] = LiteralVar.create("row")
# The gap between the items of the radio group.
- spacing: Var[LiteralSpacing] = Var.create_safe("2")
+ spacing: Var[LiteralSpacing] = LiteralVar.create("2")
# The size of the radio group.
- size: Var[Literal["1", "2", "3"]] = Var.create_safe("2")
+ size: Var[Literal["1", "2", "3"]] = LiteralVar.create("2")
# The variant of the radio group
- variant: Var[Literal["classic", "surface", "soft"]]
+ variant: Var[Literal["classic", "surface", "soft"]] = LiteralVar.create("classic")
# The color of the radio group
color_scheme: Var[LiteralAccentColor]
@@ -137,34 +133,51 @@ class HighLevelRadioGroup(RadixThemesComponent):
Returns:
The created radio group component.
+
+ Raises:
+ TypeError: If the type of items is invalid.
"""
- direction = props.pop("direction", "column")
+ direction = props.pop("direction", "row")
spacing = props.pop("spacing", "2")
size = props.pop("size", "2")
+ variant = props.pop("variant", "classic")
+ color_scheme = props.pop("color_scheme", None)
default_value = props.pop("default_value", "")
+ if (
+ not isinstance(items, (list, Var))
+ or isinstance(items, Var)
+ and not types._issubclass(items._var_type, list)
+ ):
+ items_type = type(items) if not isinstance(items, Var) else items._var_type
+ raise TypeError(
+ f"The radio group component takes in a list, got {items_type} instead"
+ )
+
+ default_value = LiteralVar.create(default_value)
+
# convert only non-strings to json(JSON.stringify) so quotes are not rendered
# for string literal types.
if isinstance(default_value, str) or (
isinstance(default_value, Var) and default_value._var_type is str
):
- default_value = Var.create(default_value, _var_is_string=True) # type: ignore
+ default_value = LiteralVar.create(default_value) # type: ignore
else:
- default_value = (
- Var.create(default_value).to_string()._replace(_var_is_local=False) # type: ignore
- )
+ default_value = LiteralVar.create(default_value).to_string()
- def radio_group_item(value: str | Var) -> Component:
- item_value = Var.create(value) # type: ignore
+ def radio_group_item(value: Var) -> Component:
item_value = rx.cond(
- item_value._type() == str, # type: ignore
- item_value,
- item_value.to_string()._replace(_var_is_local=False), # type: ignore
- )._replace(_var_type=str)
+ value.js_type() == "string",
+ value,
+ value.to_string(),
+ ).to(StringVar)
return Text.create(
Flex.create(
- RadioGroupItem.create(value=item_value),
+ RadioGroupItem.create(
+ value=item_value,
+ disabled=props.get("disabled", LiteralVar.create(False)),
+ ),
item_value,
spacing="2",
),
@@ -172,8 +185,7 @@ class HighLevelRadioGroup(RadixThemesComponent):
as_="label",
)
- items = Var.create(items) # type: ignore
- children = [rx.foreach(items, radio_group_item)]
+ children = [rx.foreach(LiteralVar.create(items), radio_group_item)]
return RadioGroupRoot.create(
Flex.create(
@@ -182,6 +194,8 @@ class HighLevelRadioGroup(RadixThemesComponent):
spacing=spacing,
),
size=size,
+ variant=variant,
+ color_scheme=color_scheme,
default_value=default_value,
**props,
)
diff --git a/reflex/components/radix/themes/components/radio_group.pyi b/reflex/components/radix/themes/components/radio_group.pyi
index ae6b73389..5ff5d6e7c 100644
--- a/reflex/components/radix/themes/components/radio_group.pyi
+++ b/reflex/components/radix/themes/components/radio_group.pyi
@@ -1,98 +1,102 @@
"""Stub file for reflex/components/radix/themes/components/radio_group.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, List, Literal, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+from reflex.components.component import ComponentNamespace
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.event import EventType
from reflex.style import Style
-from typing import Any, Dict, List, Literal, Optional, Union
-import reflex as rx
-from reflex.components.component import Component, ComponentNamespace
-from reflex.components.radix.themes.layout.flex import Flex
-from reflex.components.radix.themes.typography.text import Text
-from reflex.constants import EventTriggers
-from reflex.vars import Var
-from ..base import LiteralAccentColor, LiteralSpacing, RadixThemesComponent
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
LiteralFlexDirection = Literal["row", "column", "row-reverse", "column-reverse"]
class RadioGroupRoot(RadixThemesComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
variant: Optional[
Union[
- Var[Literal["classic", "surface", "soft"]],
- Literal["classic", "surface", "soft"],
+ Literal["classic", "soft", "surface"],
+ Var[Literal["classic", "soft", "surface"]],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
@@ -108,55 +112,23 @@ class RadioGroupRoot(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_change: Optional[EventType[str]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "RadioGroupRoot":
"""Create a new component instance.
@@ -174,6 +146,7 @@ class RadioGroupRoot(RadixThemesComponent):
disabled: Whether the radio group is disabled
name: The name of the group. Submitted with its owning form as part of a name/value pair.
required: Whether the radio group is required
+ on_change: Props to rename Fired when the value of the radio group changes.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -202,52 +175,22 @@ class RadioGroupItem(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "RadioGroupItem":
"""Create a new component instance.
@@ -278,87 +221,87 @@ class HighLevelRadioGroup(RadixThemesComponent):
def create( # type: ignore
cls,
*children,
- items: Optional[Union[Var[List[str]], List[str]]] = None,
+ items: Optional[Union[List[str], Var[List[str]]]] = None,
direction: Optional[
Union[
- Var[Literal["row", "column", "row-reverse", "column-reverse"]],
- Literal["row", "column", "row-reverse", "column-reverse"],
+ Literal["column", "column-reverse", "row", "row-reverse"],
+ Var[Literal["column", "column-reverse", "row", "row-reverse"]],
]
] = None,
spacing: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
]
] = None,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[Literal["1", "2", "3"], Var[Literal["1", "2", "3"]]]
] = None,
variant: Optional[
Union[
- Var[Literal["classic", "surface", "soft"]],
- Literal["classic", "surface", "soft"],
+ Literal["classic", "soft", "surface"],
+ Var[Literal["classic", "soft", "surface"]],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
@@ -374,52 +317,22 @@ class HighLevelRadioGroup(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "HighLevelRadioGroup":
"""Create a radio group component.
@@ -447,6 +360,9 @@ class HighLevelRadioGroup(RadixThemesComponent):
Returns:
The created radio group component.
+
+ Raises:
+ TypeError: If the type of items is invalid.
"""
...
@@ -457,87 +373,87 @@ class RadioGroup(ComponentNamespace):
@staticmethod
def __call__(
*children,
- items: Optional[Union[Var[List[str]], List[str]]] = None,
+ items: Optional[Union[List[str], Var[List[str]]]] = None,
direction: Optional[
Union[
- Var[Literal["row", "column", "row-reverse", "column-reverse"]],
- Literal["row", "column", "row-reverse", "column-reverse"],
+ Literal["column", "column-reverse", "row", "row-reverse"],
+ Var[Literal["column", "column-reverse", "row", "row-reverse"]],
]
] = None,
spacing: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
]
] = None,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[Literal["1", "2", "3"], Var[Literal["1", "2", "3"]]]
] = None,
variant: Optional[
Union[
- Var[Literal["classic", "surface", "soft"]],
- Literal["classic", "surface", "soft"],
+ Literal["classic", "soft", "surface"],
+ Var[Literal["classic", "soft", "surface"]],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
@@ -553,52 +469,22 @@ class RadioGroup(ComponentNamespace):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "HighLevelRadioGroup":
"""Create a radio group component.
@@ -626,6 +512,9 @@ class RadioGroup(ComponentNamespace):
Returns:
The created radio group component.
+
+ Raises:
+ TypeError: If the type of items is invalid.
"""
...
diff --git a/reflex/components/radix/themes/components/scroll_area.py b/reflex/components/radix/themes/components/scroll_area.py
index b7b79286b..bd58118dd 100644
--- a/reflex/components/radix/themes/components/scroll_area.py
+++ b/reflex/components/radix/themes/components/scroll_area.py
@@ -1,7 +1,8 @@
"""Interactive components provided by @radix-ui/themes."""
+
from typing import Literal
-from reflex.vars import Var
+from reflex.vars.base import Var
from ..base import (
RadixThemesComponent,
diff --git a/reflex/components/radix/themes/components/scroll_area.pyi b/reflex/components/radix/themes/components/scroll_area.pyi
index 721ec97ae..8deeb0fe9 100644
--- a/reflex/components/radix/themes/components/scroll_area.pyi
+++ b/reflex/components/radix/themes/components/scroll_area.pyi
@@ -1,14 +1,14 @@
"""Stub file for reflex/components/radix/themes/components/scroll_area.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+
+from reflex.event import EventType
from reflex.style import Style
-from typing import Literal
-from reflex.vars import Var
+from reflex.vars.base import Var
+
from ..base import RadixThemesComponent
class ScrollArea(RadixThemesComponent):
@@ -19,14 +19,14 @@ class ScrollArea(RadixThemesComponent):
*children,
scrollbars: Optional[
Union[
- Var[Literal["vertical", "horizontal", "both"]],
- Literal["vertical", "horizontal", "both"],
+ Literal["both", "horizontal", "vertical"],
+ Var[Literal["both", "horizontal", "vertical"]],
]
] = None,
type: Optional[
Union[
- Var[Literal["auto", "always", "scroll", "hover"]],
- Literal["auto", "always", "scroll", "hover"],
+ Literal["always", "auto", "hover", "scroll"],
+ Var[Literal["always", "auto", "hover", "scroll"]],
]
] = None,
scroll_hide_delay: Optional[Union[Var[int], int]] = None,
@@ -36,52 +36,22 @@ class ScrollArea(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ScrollArea":
"""Create a new component instance.
diff --git a/reflex/components/radix/themes/components/segmented_control.py b/reflex/components/radix/themes/components/segmented_control.py
index 91d7dc433..22725eaa6 100644
--- a/reflex/components/radix/themes/components/segmented_control.py
+++ b/reflex/components/radix/themes/components/segmented_control.py
@@ -1,23 +1,42 @@
"""SegmentedControl from Radix Themes."""
-from types import SimpleNamespace
-from typing import Literal
+from __future__ import annotations
-from reflex.vars import Var
+from types import SimpleNamespace
+from typing import List, Literal, Tuple, Union
+
+from reflex.components.core.breakpoints import Responsive
+from reflex.event import EventHandler
+from reflex.vars.base import Var
from ..base import LiteralAccentColor, RadixThemesComponent
+def on_value_change(value: Var[str | List[str]]) -> Tuple[Var[str | List[str]]]:
+ """Handle the on_value_change event.
+
+ Args:
+ value: The value of the event.
+
+ Returns:
+ The value of the event.
+ """
+ return (value,)
+
+
class SegmentedControlRoot(RadixThemesComponent):
"""Root element for a SegmentedControl component."""
- tag = "SegmentedControl"
+ tag = "SegmentedControl.Root"
# The size of the segmented control: "1" | "2" | "3"
- size: Var[Literal["1", "2", "3"]]
+ size: Var[Responsive[Literal["1", "2", "3"]]]
- # Variant of button: "classic" | "surface" | "soft"
- variant: Var[Literal["classic", "surface", "soft"]]
+ # Variant of button: "classic" | "surface"
+ variant: Var[Literal["classic", "surface"]]
+
+ # The type of the segmented control, either "single" for selecting one option or "multiple" for selecting multiple options.
+ type: Var[Literal["single", "multiple"]]
# Override theme color for button
color_scheme: Var[LiteralAccentColor]
@@ -26,7 +45,15 @@ class SegmentedControlRoot(RadixThemesComponent):
radius: Var[Literal["none", "small", "medium", "large", "full"]]
# The default value of the segmented control.
- default_value: Var[str]
+ default_value: Var[Union[str, List[str]]]
+
+ # The current value of the segmented control.
+ value: Var[Union[str, List[str]]]
+
+ # Handles the `onChange` event for the SegmentedControl component.
+ on_change: EventHandler[on_value_change]
+
+ _rename_props = {"onChange": "onValueChange"}
class SegmentedControlItem(RadixThemesComponent):
@@ -37,6 +64,8 @@ class SegmentedControlItem(RadixThemesComponent):
# The value of the item.
value: Var[str]
+ _valid_parents: List[str] = ["SegmentedControlRoot"]
+
class SegmentedControl(SimpleNamespace):
"""SegmentedControl components namespace."""
diff --git a/reflex/components/radix/themes/components/segmented_control.pyi b/reflex/components/radix/themes/components/segmented_control.pyi
index 26fce751a..d74c26be9 100644
--- a/reflex/components/radix/themes/components/segmented_control.pyi
+++ b/reflex/components/radix/themes/components/segmented_control.pyi
@@ -1,16 +1,19 @@
"""Stub file for reflex/components/radix/themes/components/segmented_control.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
from types import SimpleNamespace
-from typing import Literal
-from reflex.vars import Var
-from ..base import LiteralAccentColor, RadixThemesComponent
+from typing import Any, Dict, List, Literal, Optional, Tuple, Union, overload
+
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
+
+def on_value_change(value: Var[str | List[str]]) -> Tuple[Var[str | List[str]]]: ...
class SegmentedControlRoot(RadixThemesComponent):
@overload
@@ -19,135 +22,117 @@ class SegmentedControlRoot(RadixThemesComponent):
cls,
*children,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
variant: Optional[
- Union[
- Var[Literal["classic", "surface", "soft"]],
- Literal["classic", "surface", "soft"],
- ]
+ Union[Literal["classic", "surface"], Var[Literal["classic", "surface"]]]
+ ] = None,
+ type: Optional[
+ Union[Literal["multiple", "single"], Var[Literal["multiple", "single"]]]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
radius: Optional[
Union[
- Var[Literal["none", "small", "medium", "large", "full"]],
- Literal["none", "small", "medium", "large", "full"],
+ Literal["full", "large", "medium", "none", "small"],
+ Var[Literal["full", "large", "medium", "none", "small"]],
]
] = None,
- default_value: Optional[Union[Var[str], str]] = None,
+ default_value: Optional[
+ Union[List[str], Var[Union[List[str], str]], str]
+ ] = None,
+ value: Optional[Union[List[str], Var[Union[List[str], str]], str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_change: Optional[EventType[str | List[str]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "SegmentedControlRoot":
"""Create a new component instance.
@@ -157,10 +142,13 @@ class SegmentedControlRoot(RadixThemesComponent):
Args:
*children: Child components.
size: The size of the segmented control: "1" | "2" | "3"
- variant: Variant of button: "classic" | "surface" | "soft"
+ variant: Variant of button: "classic" | "surface"
+ type: The type of the segmented control, either "single" for selecting one option or "multiple" for selecting multiple options.
color_scheme: Override theme color for button
radius: The radius of the segmented control: "none" | "small" | "medium" | "large" | "full"
default_value: The default value of the segmented control.
+ value: The current value of the segmented control.
+ on_change: Handles the `onChange` event for the SegmentedControl component.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -187,52 +175,22 @@ class SegmentedControlItem(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "SegmentedControlItem":
"""Create a new component instance.
diff --git a/reflex/components/radix/themes/components/select.py b/reflex/components/radix/themes/components/select.py
index f63247f1e..47a1eaf3f 100644
--- a/reflex/components/radix/themes/components/select.py
+++ b/reflex/components/radix/themes/components/select.py
@@ -1,10 +1,12 @@
"""Interactive components provided by @radix-ui/themes."""
-from typing import Any, Dict, List, Literal, Union
+
+from typing import List, Literal, Union
import reflex as rx
from reflex.components.component import Component, ComponentNamespace
-from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.event import empty_event, identity_event
+from reflex.vars.base import Var
from ..base import (
LiteralAccentColor,
@@ -19,7 +21,7 @@ class SelectRoot(RadixThemesComponent):
tag = "Select.Root"
# The size of the select: "1" | "2" | "3"
- size: Var[Literal["1", "2", "3"]]
+ size: Var[Responsive[Literal["1", "2", "3"]]]
# The value of the select when initially rendered. Use when you do not need to control the state of the select.
default_value: Var[str]
@@ -45,17 +47,11 @@ class SelectRoot(RadixThemesComponent):
# Props to rename
_rename_props = {"onChange": "onValueChange"}
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
+ # Fired when the value of the select changes.
+ on_change: rx.EventHandler[identity_event(str)]
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_OPEN_CHANGE: lambda e0: [e0],
- EventTriggers.ON_CHANGE: lambda e0: [e0],
- }
+ # Fired when the select is opened or closed.
+ on_open_change: rx.EventHandler[identity_event(bool)]
class SelectTrigger(RadixThemesComponent):
@@ -107,18 +103,14 @@ class SelectContent(RadixThemesComponent):
# The vertical distance in pixels from the anchor. Only available when position is set to popper.
align_offset: Var[int]
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
+ # Fired when the select content is closed.
+ on_close_auto_focus: rx.EventHandler[empty_event]
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_CLOSE_AUTO_FOCUS: lambda e0: [e0],
- EventTriggers.ON_ESCAPE_KEY_DOWN: lambda e0: [e0],
- EventTriggers.ON_POINTER_DOWN_OUTSIDE: lambda e0: [e0],
- }
+ # Fired when the escape key is pressed.
+ on_escape_key_down: rx.EventHandler[empty_event]
+
+ # Fired when a pointer down event happens outside the select content.
+ on_pointer_down_outside: rx.EventHandler[empty_event]
class SelectGroup(RadixThemesComponent):
diff --git a/reflex/components/radix/themes/components/select.pyi b/reflex/components/radix/themes/components/select.pyi
index a8dfb869d..d43ac7327 100644
--- a/reflex/components/radix/themes/components/select.pyi
+++ b/reflex/components/radix/themes/components/select.pyi
@@ -1,28 +1,34 @@
"""Stub file for reflex/components/radix/themes/components/select.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, List, Literal, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+from reflex.components.component import ComponentNamespace
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.event import EventType
from reflex.style import Style
-from typing import Any, Dict, List, Literal, Union
-import reflex as rx
-from reflex.components.component import Component, ComponentNamespace
-from reflex.constants import EventTriggers
-from reflex.vars import Var
-from ..base import LiteralAccentColor, LiteralRadius, RadixThemesComponent
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
class SelectRoot(RadixThemesComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
default_value: Optional[Union[Var[str], str]] = None,
value: Optional[Union[Var[str], str]] = None,
@@ -37,58 +43,24 @@ class SelectRoot(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_open_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_change: Optional[EventType[str]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_open_change: Optional[EventType[bool]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "SelectRoot":
"""Create a new component instance.
@@ -105,6 +77,8 @@ class SelectRoot(RadixThemesComponent):
name: The name of the select control when submitting the form.
disabled: When True, prevents the user from interacting with select.
required: When True, indicates that the user must select a value before the owning form can be submitted.
+ on_change: Props to rename Fired when the value of the select changes.
+ on_open_change: Fired when the select is opened or closed.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -126,76 +100,76 @@ class SelectTrigger(RadixThemesComponent):
*children,
variant: Optional[
Union[
- Var[Literal["classic", "surface", "soft", "ghost"]],
- Literal["classic", "surface", "soft", "ghost"],
+ Literal["classic", "ghost", "soft", "surface"],
+ Var[Literal["classic", "ghost", "soft", "surface"]],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
radius: Optional[
Union[
- Var[Literal["none", "small", "medium", "large", "full"]],
- Literal["none", "small", "medium", "large", "full"],
+ Literal["full", "large", "medium", "none", "small"],
+ Var[Literal["full", "large", "medium", "none", "small"]],
]
] = None,
placeholder: Optional[Union[Var[str], str]] = None,
@@ -205,52 +179,22 @@ class SelectTrigger(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "SelectTrigger":
"""Create a new component instance.
@@ -277,95 +221,94 @@ class SelectTrigger(RadixThemesComponent):
...
class SelectContent(RadixThemesComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
variant: Optional[
- Union[Var[Literal["solid", "soft"]], Literal["solid", "soft"]]
+ Union[Literal["soft", "solid"], Var[Literal["soft", "solid"]]]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
position: Optional[
Union[
- Var[Literal["item-aligned", "popper"]],
Literal["item-aligned", "popper"],
+ Var[Literal["item-aligned", "popper"]],
]
] = None,
side: Optional[
Union[
- Var[Literal["top", "right", "bottom", "left"]],
- Literal["top", "right", "bottom", "left"],
+ Literal["bottom", "left", "right", "top"],
+ Var[Literal["bottom", "left", "right", "top"]],
]
] = None,
side_offset: Optional[Union[Var[int], int]] = None,
align: Optional[
Union[
- Var[Literal["start", "center", "end"]],
- Literal["start", "center", "end"],
+ Literal["center", "end", "start"],
+ Var[Literal["center", "end", "start"]],
]
] = None,
align_offset: Optional[Union[Var[int], int]] = None,
@@ -375,61 +318,25 @@ class SelectContent(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_close_auto_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_escape_key_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_pointer_down_outside: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_close_auto_focus: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_escape_key_down: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_pointer_down_outside: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "SelectContent":
"""Create a new component instance.
@@ -446,6 +353,9 @@ class SelectContent(RadixThemesComponent):
side_offset: The distance in pixels from the anchor. Only available when position is set to popper.
align: The preferred alignment against the anchor. May change when collisions occur. Only available when position is set to popper.
align_offset: The vertical distance in pixels from the anchor. Only available when position is set to popper.
+ on_close_auto_focus: Fired when the select content is closed.
+ on_escape_key_down: Fired when the escape key is pressed.
+ on_pointer_down_outside: Fired when a pointer down event happens outside the select content.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -471,52 +381,22 @@ class SelectGroup(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "SelectGroup":
"""Create a new component instance.
@@ -552,52 +432,22 @@ class SelectItem(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "SelectItem":
"""Create a new component instance.
@@ -633,52 +483,22 @@ class SelectLabel(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "SelectLabel":
"""Create a new component instance.
@@ -712,52 +532,22 @@ class SelectSeparator(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "SelectSeparator":
"""Create a new component instance.
@@ -785,93 +575,101 @@ class HighLevelSelect(SelectRoot):
def create( # type: ignore
cls,
*children,
- items: Optional[Union[Var[List[str]], List[str]]] = None,
+ items: Optional[Union[List[str], Var[List[str]]]] = None,
placeholder: Optional[Union[Var[str], str]] = None,
label: Optional[Union[Var[str], str]] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
variant: Optional[
Union[
- Var[Literal["classic", "surface", "soft", "ghost"]],
- Literal["classic", "surface", "soft", "ghost"],
+ Literal["classic", "ghost", "soft", "surface"],
+ Var[Literal["classic", "ghost", "soft", "surface"]],
]
] = None,
radius: Optional[
Union[
- Var[Literal["none", "small", "medium", "large", "full"]],
- Literal["none", "small", "medium", "large", "full"],
+ Literal["full", "large", "medium", "none", "small"],
+ Var[Literal["full", "large", "medium", "none", "small"]],
]
] = None,
width: Optional[Union[Var[str], str]] = None,
position: Optional[
Union[
- Var[Literal["item-aligned", "popper"]],
Literal["item-aligned", "popper"],
+ Var[Literal["item-aligned", "popper"]],
]
] = None,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
default_value: Optional[Union[Var[str], str]] = None,
value: Optional[Union[Var[str], str]] = None,
@@ -886,58 +684,24 @@ class HighLevelSelect(SelectRoot):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_open_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_change: Optional[EventType[str]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_open_change: Optional[EventType[bool]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "HighLevelSelect":
"""Create a select component.
@@ -960,6 +724,8 @@ class HighLevelSelect(SelectRoot):
name: The name of the select control when submitting the form.
disabled: When True, prevents the user from interacting with select.
required: When True, indicates that the user must select a value before the owning form can be submitted.
+ on_change: Props to rename Fired when the value of the select changes.
+ on_open_change: Fired when the select is opened or closed.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -985,93 +751,101 @@ class Select(ComponentNamespace):
@staticmethod
def __call__(
*children,
- items: Optional[Union[Var[List[str]], List[str]]] = None,
+ items: Optional[Union[List[str], Var[List[str]]]] = None,
placeholder: Optional[Union[Var[str], str]] = None,
label: Optional[Union[Var[str], str]] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
variant: Optional[
Union[
- Var[Literal["classic", "surface", "soft", "ghost"]],
- Literal["classic", "surface", "soft", "ghost"],
+ Literal["classic", "ghost", "soft", "surface"],
+ Var[Literal["classic", "ghost", "soft", "surface"]],
]
] = None,
radius: Optional[
Union[
- Var[Literal["none", "small", "medium", "large", "full"]],
- Literal["none", "small", "medium", "large", "full"],
+ Literal["full", "large", "medium", "none", "small"],
+ Var[Literal["full", "large", "medium", "none", "small"]],
]
] = None,
width: Optional[Union[Var[str], str]] = None,
position: Optional[
Union[
- Var[Literal["item-aligned", "popper"]],
Literal["item-aligned", "popper"],
+ Var[Literal["item-aligned", "popper"]],
]
] = None,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
default_value: Optional[Union[Var[str], str]] = None,
value: Optional[Union[Var[str], str]] = None,
@@ -1086,58 +860,24 @@ class Select(ComponentNamespace):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_open_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_change: Optional[EventType[str]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_open_change: Optional[EventType[bool]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "HighLevelSelect":
"""Create a select component.
@@ -1160,6 +900,8 @@ class Select(ComponentNamespace):
name: The name of the select control when submitting the form.
disabled: When True, prevents the user from interacting with select.
required: When True, indicates that the user must select a value before the owning form can be submitted.
+ on_change: Props to rename Fired when the value of the select changes.
+ on_open_change: Fired when the select is opened or closed.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
diff --git a/reflex/components/radix/themes/components/separator.py b/reflex/components/radix/themes/components/separator.py
index 92d2e8b85..1689717d2 100644
--- a/reflex/components/radix/themes/components/separator.py
+++ b/reflex/components/radix/themes/components/separator.py
@@ -1,7 +1,9 @@
"""Interactive components provided by @radix-ui/themes."""
+
from typing import Literal
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.vars.base import LiteralVar, Var
from ..base import (
LiteralAccentColor,
@@ -17,13 +19,13 @@ class Separator(RadixThemesComponent):
tag = "Separator"
# The size of the select: "1" | "2" | "3" | "4"
- size: Var[LiteralSeperatorSize] = Var.create_safe("4")
+ size: Var[Responsive[LiteralSeperatorSize]] = LiteralVar.create("4")
# The color of the select
color_scheme: Var[LiteralAccentColor]
# The orientation of the separator.
- orientation: Var[Literal["horizontal", "vertical"]]
+ orientation: Var[Responsive[Literal["horizontal", "vertical"]]]
# When true, signifies that it is purely visual, carries no semantic meaning, and ensures it is not present in the accessibility tree.
decorative: Var[bool]
diff --git a/reflex/components/radix/themes/components/separator.pyi b/reflex/components/radix/themes/components/separator.pyi
index 6e88bc4dd..0f2895403 100644
--- a/reflex/components/radix/themes/components/separator.pyi
+++ b/reflex/components/radix/themes/components/separator.pyi
@@ -1,15 +1,16 @@
"""Stub file for reflex/components/radix/themes/components/separator.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.event import EventType
from reflex.style import Style
-from typing import Literal
-from reflex.vars import Var
-from ..base import LiteralAccentColor, RadixThemesComponent
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
LiteralSeperatorSize = Literal["1", "2", "3", "4"]
@@ -20,74 +21,89 @@ class Separator(RadixThemesComponent):
cls,
*children,
size: Optional[
- Union[Var[Literal["1", "2", "3", "4"]], Literal["1", "2", "3", "4"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3", "4"]],
+ Literal["1", "2", "3", "4"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3", "4"]],
+ Literal["1", "2", "3", "4"],
+ ]
+ ],
+ ]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
orientation: Optional[
Union[
- Var[Literal["horizontal", "vertical"]],
+ Breakpoints[str, Literal["horizontal", "vertical"]],
Literal["horizontal", "vertical"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["horizontal", "vertical"]],
+ Literal["horizontal", "vertical"],
+ ]
+ ],
]
] = None,
decorative: Optional[Union[Var[bool], bool]] = None,
@@ -97,52 +113,22 @@ class Separator(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Separator":
"""Create a new component instance.
diff --git a/reflex/components/radix/themes/components/skeleton.py b/reflex/components/radix/themes/components/skeleton.py
index 986e7783b..1fb6390a1 100644
--- a/reflex/components/radix/themes/components/skeleton.py
+++ b/reflex/components/radix/themes/components/skeleton.py
@@ -1,6 +1,7 @@
"""Skeleton theme from Radix components."""
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.vars.base import Var
from ..base import RadixLoadingProp, RadixThemesComponent
@@ -11,22 +12,22 @@ class Skeleton(RadixLoadingProp, RadixThemesComponent):
tag = "Skeleton"
# The width of the skeleton
- width: Var[str]
+ width: Var[Responsive[str]]
# The minimum width of the skeleton
- min_width: Var[str]
+ min_width: Var[Responsive[str]]
# The maximum width of the skeleton
- max_width: Var[str]
+ max_width: Var[Responsive[str]]
# The height of the skeleton
- height: Var[str]
+ height: Var[Responsive[str]]
# The minimum height of the skeleton
- min_height: Var[str]
+ min_height: Var[Responsive[str]]
# The maximum height of the skeleton
- max_height: Var[str]
+ max_height: Var[Responsive[str]]
skeleton = Skeleton.create
diff --git a/reflex/components/radix/themes/components/skeleton.pyi b/reflex/components/radix/themes/components/skeleton.pyi
index 23f180791..61b57c275 100644
--- a/reflex/components/radix/themes/components/skeleton.pyi
+++ b/reflex/components/radix/themes/components/skeleton.pyi
@@ -1,13 +1,15 @@
"""Stub file for reflex/components/radix/themes/components/skeleton.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.event import EventType
from reflex.style import Style
-from reflex.vars import Var
+from reflex.vars.base import Var
+
from ..base import RadixLoadingProp, RadixThemesComponent
class Skeleton(RadixLoadingProp, RadixThemesComponent):
@@ -16,12 +18,24 @@ class Skeleton(RadixLoadingProp, RadixThemesComponent):
def create( # type: ignore
cls,
*children,
- width: Optional[Union[Var[str], str]] = None,
- min_width: Optional[Union[Var[str], str]] = None,
- max_width: Optional[Union[Var[str], str]] = None,
- height: Optional[Union[Var[str], str]] = None,
- min_height: Optional[Union[Var[str], str]] = None,
- max_height: Optional[Union[Var[str], str]] = None,
+ width: Optional[
+ Union[Breakpoints[str, str], Var[Union[Breakpoints[str, str], str]], str]
+ ] = None,
+ min_width: Optional[
+ Union[Breakpoints[str, str], Var[Union[Breakpoints[str, str], str]], str]
+ ] = None,
+ max_width: Optional[
+ Union[Breakpoints[str, str], Var[Union[Breakpoints[str, str], str]], str]
+ ] = None,
+ height: Optional[
+ Union[Breakpoints[str, str], Var[Union[Breakpoints[str, str], str]], str]
+ ] = None,
+ min_height: Optional[
+ Union[Breakpoints[str, str], Var[Union[Breakpoints[str, str], str]], str]
+ ] = None,
+ max_height: Optional[
+ Union[Breakpoints[str, str], Var[Union[Breakpoints[str, str], str]], str]
+ ] = None,
loading: Optional[Union[Var[bool], bool]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
@@ -29,52 +43,22 @@ class Skeleton(RadixLoadingProp, RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Skeleton":
"""Create a new component instance.
diff --git a/reflex/components/radix/themes/components/slider.py b/reflex/components/radix/themes/components/slider.py
index 6d8bd90f1..4f456cdca 100644
--- a/reflex/components/radix/themes/components/slider.py
+++ b/reflex/components/radix/themes/components/slider.py
@@ -1,15 +1,25 @@
"""Interactive components provided by @radix-ui/themes."""
-from typing import Any, Dict, List, Literal, Optional, Union
+
+from __future__ import annotations
+
+from typing import List, Literal, Optional, Union
from reflex.components.component import Component
-from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.event import EventHandler, identity_event
+from reflex.vars.base import Var
from ..base import (
LiteralAccentColor,
RadixThemesComponent,
)
+on_value_event_spec = (
+ identity_event(list[Union[int, float]]),
+ identity_event(list[int]),
+ identity_event(list[float]),
+)
+
class Slider(RadixThemesComponent):
"""Provides user selection from a range of values."""
@@ -20,7 +30,7 @@ class Slider(RadixThemesComponent):
as_child: Var[bool]
# Button size "1" - "3"
- size: Var[Literal["1", "2", "3"]]
+ size: Var[Responsive[Literal["1", "2", "3"]]]
# Variant of button
variant: Var[Literal["classic", "surface", "soft"]]
@@ -43,6 +53,9 @@ class Slider(RadixThemesComponent):
# The name of the slider. Submitted with its owning form as part of a name/value pair.
name: Var[str]
+ # The width of the slider.
+ width: Var[Optional[str]] = Var.create("100%")
+
# The minimum value of the slider.
min: Var[Union[float, int]]
@@ -61,36 +74,29 @@ class Slider(RadixThemesComponent):
# Props to rename
_rename_props = {"onChange": "onValueChange"}
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
+ # Fired when the value of the slider changes.
+ on_change: EventHandler[on_value_event_spec]
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_CHANGE: lambda e0: [e0],
- EventTriggers.ON_VALUE_COMMIT: lambda e0: [e0],
- }
+ # Fired when a thumb is released after being dragged.
+ on_value_commit: EventHandler[on_value_event_spec]
@classmethod
def create(
cls,
*children,
- width: Optional[str] = "100%",
**props,
) -> Component:
"""Create a Slider component.
Args:
*children: The children of the component.
- width: The width of the slider.
**props: The properties of the component.
Returns:
The component.
"""
default_value = props.pop("default_value", [50])
+ width = props.pop("width", "100%")
if isinstance(default_value, Var):
if issubclass(default_value._var_type, (int, float)):
diff --git a/reflex/components/radix/themes/components/slider.pyi b/reflex/components/radix/themes/components/slider.pyi
index 5a170c542..f77573d44 100644
--- a/reflex/components/radix/themes/components/slider.pyi
+++ b/reflex/components/radix/themes/components/slider.pyi
@@ -1,122 +1,136 @@
"""Stub file for reflex/components/radix/themes/components/slider.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, List, Literal, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.event import EventType, identity_event
from reflex.style import Style
-from typing import Any, Dict, List, Literal, Optional, Union
-from reflex.components.component import Component
-from reflex.constants import EventTriggers
-from reflex.vars import Var
-from ..base import LiteralAccentColor, RadixThemesComponent
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
+
+on_value_event_spec = (
+ identity_event(list[Union[int, float]]),
+ identity_event(list[int]),
+ identity_event(list[float]),
+)
class Slider(RadixThemesComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- width: Optional[str] = "100%",
as_child: Optional[Union[Var[bool], bool]] = None,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
variant: Optional[
Union[
- Var[Literal["classic", "surface", "soft"]],
- Literal["classic", "surface", "soft"],
+ Literal["classic", "soft", "surface"],
+ Var[Literal["classic", "soft", "surface"]],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
radius: Optional[
Union[
- Var[Literal["none", "small", "full"]], Literal["none", "small", "full"]
+ Literal["full", "none", "small"], Var[Literal["full", "none", "small"]]
]
] = None,
default_value: Optional[
Union[
+ List[Union[float, int]],
Var[Union[List[Union[float, int]], float, int]],
- Union[List[Union[float, int]], float, int],
+ float,
+ int,
]
] = None,
value: Optional[
- Union[Var[List[Union[float, int]]], List[Union[float, int]]]
+ Union[List[Union[float, int]], Var[List[Union[float, int]]]]
] = None,
name: Optional[Union[Var[str], str]] = None,
- min: Optional[Union[Var[Union[float, int]], Union[float, int]]] = None,
- max: Optional[Union[Var[Union[float, int]], Union[float, int]]] = None,
- step: Optional[Union[Var[Union[float, int]], Union[float, int]]] = None,
+ width: Optional[Union[Var[Optional[str]], str]] = None,
+ min: Optional[Union[Var[Union[float, int]], float, int]] = None,
+ max: Optional[Union[Var[Union[float, int]], float, int]] = None,
+ step: Optional[Union[Var[Union[float, int]], float, int]] = None,
disabled: Optional[Union[Var[bool], bool]] = None,
orientation: Optional[
Union[
- Var[Literal["horizontal", "vertical"]],
Literal["horizontal", "vertical"],
+ Var[Literal["horizontal", "vertical"]],
]
] = None,
style: Optional[Style] = None,
@@ -125,64 +139,41 @@ class Slider(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
+ on_blur: Optional[EventType[[]]] = None,
on_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
+ Union[
+ EventType[list[Union[int, float]]],
+ EventType[list[int]],
+ EventType[list[float]],
+ ]
] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
on_value_commit: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
+ Union[
+ EventType[list[Union[int, float]]],
+ EventType[list[int]],
+ EventType[list[float]],
+ ]
] = None,
- **props
+ **props,
) -> "Slider":
"""Create a Slider component.
Args:
*children: The children of the component.
- width: The width of the slider.
as_child: Change the default rendered element for the one passed as a child, merging their props and behavior.
size: Button size "1" - "3"
variant: Variant of button
@@ -192,11 +183,14 @@ class Slider(RadixThemesComponent):
default_value: The value of the slider when initially rendered. Use when you do not need to control the state of the slider.
value: The controlled value of the slider. Must be used in conjunction with onValueChange.
name: The name of the slider. Submitted with its owning form as part of a name/value pair.
+ width: The width of the slider.
min: The minimum value of the slider.
max: The maximum value of the slider.
step: The step value of the slider.
disabled: Whether the slider is disabled
orientation: The orientation of the slider.
+ on_change: Props to rename Fired when the value of the slider changes.
+ on_value_commit: Fired when a thumb is released after being dragged.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
diff --git a/reflex/components/radix/themes/components/spinner.py b/reflex/components/radix/themes/components/spinner.py
index 4726e95ee..cc29d6091 100644
--- a/reflex/components/radix/themes/components/spinner.py
+++ b/reflex/components/radix/themes/components/spinner.py
@@ -2,7 +2,8 @@
from typing import Literal
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.vars.base import Var
from ..base import (
RadixLoadingProp,
@@ -20,7 +21,7 @@ class Spinner(RadixLoadingProp, RadixThemesComponent):
is_default = False
# The size of the spinner.
- size: Var[LiteralSpinnerSize]
+ size: Var[Responsive[LiteralSpinnerSize]]
spinner = Spinner.create
diff --git a/reflex/components/radix/themes/components/spinner.pyi b/reflex/components/radix/themes/components/spinner.pyi
index cbc9ae200..87033f05c 100644
--- a/reflex/components/radix/themes/components/spinner.pyi
+++ b/reflex/components/radix/themes/components/spinner.pyi
@@ -1,14 +1,15 @@
"""Stub file for reflex/components/radix/themes/components/spinner.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.event import EventType
from reflex.style import Style
-from typing import Literal
-from reflex.vars import Var
+from reflex.vars.base import Var
+
from ..base import RadixLoadingProp, RadixThemesComponent
LiteralSpinnerSize = Literal["1", "2", "3"]
@@ -20,7 +21,15 @@ class Spinner(RadixLoadingProp, RadixThemesComponent):
cls,
*children,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
loading: Optional[Union[Var[bool], bool]] = None,
style: Optional[Style] = None,
@@ -29,52 +38,22 @@ class Spinner(RadixLoadingProp, RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Spinner":
"""Create a new component instance.
diff --git a/reflex/components/radix/themes/components/switch.py b/reflex/components/radix/themes/components/switch.py
index 14ac152b2..13be32d83 100644
--- a/reflex/components/radix/themes/components/switch.py
+++ b/reflex/components/radix/themes/components/switch.py
@@ -1,8 +1,10 @@
"""Interactive components provided by @radix-ui/themes."""
-from typing import Any, Dict, Literal
-from reflex.constants import EventTriggers
-from reflex.vars import Var
+from typing import Literal
+
+from reflex.components.core.breakpoints import Responsive
+from reflex.event import EventHandler, identity_event
+from reflex.vars.base import Var
from ..base import (
LiteralAccentColor,
@@ -39,7 +41,7 @@ class Switch(RadixThemesComponent):
value: Var[str]
# Switch size "1" - "4"
- size: Var[LiteralSwitchSize]
+ size: Var[Responsive[LiteralSwitchSize]]
# Variant of switch: "classic" | "surface" | "soft"
variant: Var[Literal["classic", "surface", "soft"]]
@@ -56,16 +58,8 @@ class Switch(RadixThemesComponent):
# Props to rename
_rename_props = {"onChange": "onCheckedChange"}
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the event triggers that pass the component's value to the handler.
-
- Returns:
- A dict mapping the event trigger name to the argspec passed to the handler.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_CHANGE: lambda checked: [checked],
- }
+ # Fired when the value of the switch changes
+ on_change: EventHandler[identity_event(bool)]
switch = Switch.create
diff --git a/reflex/components/radix/themes/components/switch.pyi b/reflex/components/radix/themes/components/switch.pyi
index 0d40928ef..aebeb761e 100644
--- a/reflex/components/radix/themes/components/switch.pyi
+++ b/reflex/components/radix/themes/components/switch.pyi
@@ -1,21 +1,20 @@
"""Stub file for reflex/components/radix/themes/components/switch.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.event import EventType
from reflex.style import Style
-from typing import Any, Dict, Literal
-from reflex.constants import EventTriggers
-from reflex.vars import Var
-from ..base import LiteralAccentColor, RadixThemesComponent
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
LiteralSwitchSize = Literal["1", "2", "3"]
class Switch(RadixThemesComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
@@ -29,80 +28,88 @@ class Switch(RadixThemesComponent):
name: Optional[Union[Var[str], str]] = None,
value: Optional[Union[Var[str], str]] = None,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
variant: Optional[
Union[
- Var[Literal["classic", "surface", "soft"]],
- Literal["classic", "surface", "soft"],
+ Literal["classic", "soft", "surface"],
+ Var[Literal["classic", "soft", "surface"]],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
radius: Optional[
Union[
- Var[Literal["none", "small", "full"]], Literal["none", "small", "full"]
+ Literal["full", "none", "small"], Var[Literal["full", "none", "small"]]
]
] = None,
style: Optional[Style] = None,
@@ -111,55 +118,23 @@ class Switch(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_change: Optional[EventType[bool]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Switch":
"""Create a new component instance.
@@ -180,6 +155,7 @@ class Switch(RadixThemesComponent):
color_scheme: Override theme color for switch
high_contrast: Whether to render the switch with higher contrast color against background
radius: Override theme radius for switch: "none" | "small" | "full"
+ on_change: Props to rename Fired when the value of the switch changes
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
diff --git a/reflex/components/radix/themes/components/table.py b/reflex/components/radix/themes/components/table.py
index a2b3bada3..e1f03d4e2 100644
--- a/reflex/components/radix/themes/components/table.py
+++ b/reflex/components/radix/themes/components/table.py
@@ -1,28 +1,30 @@
"""Interactive components provided by @radix-ui/themes."""
+
from typing import List, Literal
-from reflex import el
from reflex.components.component import ComponentNamespace
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.components.el import elements
+from reflex.vars.base import Var
from ..base import (
RadixThemesComponent,
)
-class TableRoot(el.Table, RadixThemesComponent):
+class TableRoot(elements.Table, RadixThemesComponent):
"""A semantic table for presenting tabular data."""
tag = "Table.Root"
# The size of the table: "1" | "2" | "3"
- size: Var[Literal["1", "2", "3"]]
+ size: Var[Responsive[Literal["1", "2", "3"]]]
# The variant of the table
variant: Var[Literal["surface", "ghost"]]
-class TableHeader(el.Thead, RadixThemesComponent):
+class TableHeader(elements.Thead, RadixThemesComponent):
"""The header of the table defines column names and other non-data elements."""
tag = "Table.Header"
@@ -32,7 +34,7 @@ class TableHeader(el.Thead, RadixThemesComponent):
_valid_parents: List[str] = ["TableRoot"]
-class TableRow(el.Tr, RadixThemesComponent):
+class TableRow(elements.Tr, RadixThemesComponent):
"""A row containing table cells."""
tag = "Table.Row"
@@ -43,7 +45,7 @@ class TableRow(el.Tr, RadixThemesComponent):
_invalid_children: List[str] = ["TableBody", "TableHeader", "TableRow"]
-class TableColumnHeaderCell(el.Th, RadixThemesComponent):
+class TableColumnHeaderCell(elements.Th, RadixThemesComponent):
"""A table cell that is semantically treated as a column header."""
tag = "Table.ColumnHeaderCell"
@@ -61,7 +63,7 @@ class TableColumnHeaderCell(el.Th, RadixThemesComponent):
]
-class TableBody(el.Tbody, RadixThemesComponent):
+class TableBody(elements.Tbody, RadixThemesComponent):
"""The body of the table contains the data rows."""
tag = "Table.Body"
@@ -76,7 +78,7 @@ class TableBody(el.Tbody, RadixThemesComponent):
_valid_parents: List[str] = ["TableRoot"]
-class TableCell(el.Td, RadixThemesComponent):
+class TableCell(elements.Td, RadixThemesComponent):
"""A cell containing data."""
tag = "Table.Cell"
@@ -93,7 +95,7 @@ class TableCell(el.Td, RadixThemesComponent):
]
-class TableRowHeaderCell(el.Th, RadixThemesComponent):
+class TableRowHeaderCell(elements.Th, RadixThemesComponent):
"""A table cell that is semantically treated as a row header."""
tag = "Table.RowHeaderCell"
diff --git a/reflex/components/radix/themes/components/table.pyi b/reflex/components/radix/themes/components/table.pyi
index 5669d717c..8b1ef355f 100644
--- a/reflex/components/radix/themes/components/table.pyi
+++ b/reflex/components/radix/themes/components/table.pyi
@@ -1,128 +1,87 @@
"""Stub file for reflex/components/radix/themes/components/table.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import List, Literal
-from reflex import el
+
from reflex.components.component import ComponentNamespace
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.components.el import elements
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
+
from ..base import RadixThemesComponent
-class TableRoot(el.Table, RadixThemesComponent):
+class TableRoot(elements.Table, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
cls,
*children,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
variant: Optional[
- Union[Var[Literal["surface", "ghost"]], Literal["surface", "ghost"]]
- ] = None,
- align: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- summary: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Literal["ghost", "surface"], Var[Literal["ghost", "surface"]]]
] = None,
+ align: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ summary: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "TableRoot":
"""Create a new component instance.
@@ -164,107 +123,59 @@ class TableRoot(el.Table, RadixThemesComponent):
"""
...
-class TableHeader(el.Thead, RadixThemesComponent):
+class TableHeader(elements.Thead, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- align: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ align: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "TableHeader":
"""Create a new component instance.
@@ -303,7 +214,7 @@ class TableHeader(el.Thead, RadixThemesComponent):
"""
...
-class TableRow(el.Tr, RadixThemesComponent):
+class TableRow(elements.Tr, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
@@ -311,102 +222,56 @@ class TableRow(el.Tr, RadixThemesComponent):
*children,
align: Optional[
Union[
- Var[Literal["start", "center", "end", "baseline"]],
- Literal["start", "center", "end", "baseline"],
+ Literal["baseline", "center", "end", "start"],
+ Var[Literal["baseline", "center", "end", "start"]],
]
] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "TableRow":
"""Create a new component instance.
@@ -445,7 +310,7 @@ class TableRow(el.Tr, RadixThemesComponent):
"""
...
-class TableColumnHeaderCell(el.Th, RadixThemesComponent):
+class TableColumnHeaderCell(elements.Th, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
@@ -453,117 +318,61 @@ class TableColumnHeaderCell(el.Th, RadixThemesComponent):
*children,
justify: Optional[
Union[
- Var[Literal["start", "center", "end"]],
- Literal["start", "center", "end"],
+ Literal["center", "end", "start"],
+ Var[Literal["center", "end", "start"]],
]
] = None,
- align: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- col_span: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- headers: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- row_span: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- scope: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ align: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ col_span: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ headers: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ row_span: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ scope: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "TableColumnHeaderCell":
"""Create a new component instance.
@@ -607,107 +416,59 @@ class TableColumnHeaderCell(el.Th, RadixThemesComponent):
"""
...
-class TableBody(el.Tbody, RadixThemesComponent):
+class TableBody(elements.Tbody, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- align: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ align: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "TableBody":
"""Create a new component instance.
@@ -746,7 +507,7 @@ class TableBody(el.Tbody, RadixThemesComponent):
"""
...
-class TableCell(el.Td, RadixThemesComponent):
+class TableCell(elements.Td, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
@@ -754,114 +515,60 @@ class TableCell(el.Td, RadixThemesComponent):
*children,
justify: Optional[
Union[
- Var[Literal["start", "center", "end"]],
- Literal["start", "center", "end"],
+ Literal["center", "end", "start"],
+ Var[Literal["center", "end", "start"]],
]
] = None,
- align: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- col_span: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- headers: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- row_span: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ align: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ col_span: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ headers: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ row_span: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "TableCell":
"""Create a new component instance.
@@ -904,7 +611,7 @@ class TableCell(el.Td, RadixThemesComponent):
"""
...
-class TableRowHeaderCell(el.Th, RadixThemesComponent):
+class TableRowHeaderCell(elements.Th, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
@@ -912,117 +619,61 @@ class TableRowHeaderCell(el.Th, RadixThemesComponent):
*children,
justify: Optional[
Union[
- Var[Literal["start", "center", "end"]],
- Literal["start", "center", "end"],
+ Literal["center", "end", "start"],
+ Var[Literal["center", "end", "start"]],
]
] = None,
- align: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- col_span: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- headers: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- row_span: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- scope: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ align: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ col_span: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ headers: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ row_span: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ scope: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "TableRowHeaderCell":
"""Create a new component instance.
diff --git a/reflex/components/radix/themes/components/tabs.py b/reflex/components/radix/themes/components/tabs.py
index af1b6b521..12359b528 100644
--- a/reflex/components/radix/themes/components/tabs.py
+++ b/reflex/components/radix/themes/components/tabs.py
@@ -1,17 +1,22 @@
"""Interactive components provided by @radix-ui/themes."""
+
from __future__ import annotations
from typing import Any, Dict, List, Literal
from reflex.components.component import Component, ComponentNamespace
-from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.components.core.colors import color
+from reflex.event import EventHandler, identity_event
+from reflex.vars.base import Var
from ..base import (
LiteralAccentColor,
RadixThemesComponent,
)
+vertical_orientation_css = "&[data-orientation='vertical']"
+
class TabsRoot(RadixThemesComponent):
"""Set of content sections to be displayed one at a time."""
@@ -27,18 +32,28 @@ class TabsRoot(RadixThemesComponent):
# The orientation of the tabs.
orientation: Var[Literal["horizontal", "vertical"]]
+ # Reading direction of the tabs.
+ dir: Var[Literal["ltr", "rtl"]]
+
+ # The mode of activation for the tabs. "automatic" will activate the tab when focused. "manual" will activate the tab when clicked.
+ activation_mode: Var[Literal["automatic", "manual"]]
+
# Props to rename
_rename_props = {"onChange": "onValueChange"}
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
+ # Fired when the value of the tabs changes.
+ on_change: EventHandler[identity_event(str)]
+
+ def add_style(self) -> Dict[str, Any] | None:
+ """Add style for the component.
Returns:
- The signatures of the event triggers.
+ The style to add.
"""
return {
- **super().get_event_triggers(),
- EventTriggers.ON_CHANGE: lambda e0: [e0],
+ vertical_orientation_css: {
+ "display": "flex",
+ }
}
@@ -48,7 +63,23 @@ class TabsList(RadixThemesComponent):
tag = "Tabs.List"
# Tabs size "1" - "2"
- size: Var[Literal["1", "2"]]
+ size: Var[Responsive[Literal["1", "2"]]]
+
+ # When true, the tabs will loop when reaching the end.
+ loop: Var[bool]
+
+ def add_style(self):
+ """Add style for the component.
+
+ Returns:
+ The style to add.
+ """
+ return {
+ vertical_orientation_css: {
+ "display": "block",
+ "box_shadow": f"inset -1px 0 0 0 {color('gray', 5, alpha=True)}",
+ },
+ }
class TabsTrigger(RadixThemesComponent):
@@ -68,7 +99,7 @@ class TabsTrigger(RadixThemesComponent):
_valid_parents: List[str] = ["TabsList"]
@classmethod
- def create(self, *children, **props) -> Component:
+ def create(cls, *children, **props) -> Component:
"""Create a TabsTrigger component.
Args:
@@ -86,6 +117,14 @@ class TabsTrigger(RadixThemesComponent):
def _exclude_props(self) -> list[str]:
return ["color_scheme"]
+ def add_style(self) -> Dict[str, Any] | None:
+ """Add style for the component.
+
+ Returns:
+ The style to add.
+ """
+ return {vertical_orientation_css: {"width": "100%"}}
+
class TabsContent(RadixThemesComponent):
"""Contains the content associated with each trigger."""
@@ -95,6 +134,19 @@ class TabsContent(RadixThemesComponent):
# The value of the tab. Must be unique for each tab.
value: Var[str]
+ # Used to force mounting when more control is needed. Useful when controlling animation with React animation libraries.
+ force_mount: Var[bool]
+
+ def add_style(self) -> dict[str, Any] | None:
+ """Add style for the component.
+
+ Returns:
+ The style to add.
+ """
+ return {
+ vertical_orientation_css: {"width": "100%", "margin": None},
+ }
+
class Tabs(ComponentNamespace):
"""Set of content sections to be displayed one at a time."""
diff --git a/reflex/components/radix/themes/components/tabs.pyi b/reflex/components/radix/themes/components/tabs.pyi
index a8243554f..ac6109209 100644
--- a/reflex/components/radix/themes/components/tabs.pyi
+++ b/reflex/components/radix/themes/components/tabs.pyi
@@ -1,20 +1,22 @@
"""Stub file for reflex/components/radix/themes/components/tabs.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+
+from reflex.components.component import ComponentNamespace
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.event import EventType
from reflex.style import Style
-from typing import Any, Dict, List, Literal
-from reflex.components.component import Component, ComponentNamespace
-from reflex.constants import EventTriggers
-from reflex.vars import Var
-from ..base import LiteralAccentColor, RadixThemesComponent
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
+
+vertical_orientation_css = "&[data-orientation='vertical']"
class TabsRoot(RadixThemesComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
+ def add_style(self) -> Dict[str, Any] | None: ...
@overload
@classmethod
def create( # type: ignore
@@ -24,65 +26,37 @@ class TabsRoot(RadixThemesComponent):
value: Optional[Union[Var[str], str]] = None,
orientation: Optional[
Union[
- Var[Literal["horizontal", "vertical"]],
Literal["horizontal", "vertical"],
+ Var[Literal["horizontal", "vertical"]],
]
] = None,
+ dir: Optional[Union[Literal["ltr", "rtl"], Var[Literal["ltr", "rtl"]]]] = None,
+ activation_mode: Optional[
+ Union[Literal["automatic", "manual"], Var[Literal["automatic", "manual"]]]
+ ] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_change: Optional[EventType[str]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "TabsRoot":
"""Create a new component instance.
@@ -94,6 +68,9 @@ class TabsRoot(RadixThemesComponent):
default_value: The value of the tab that should be active when initially rendered. Use when you do not need to control the state of the tabs.
value: The controlled value of the tab that should be active. Use when you need to control the state of the tabs.
orientation: The orientation of the tabs.
+ dir: Reading direction of the tabs.
+ activation_mode: The mode of activation for the tabs. "automatic" will activate the tab when focused. "manual" will activate the tab when clicked.
+ on_change: Props to rename Fired when the value of the tabs changes.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -108,64 +85,42 @@ class TabsRoot(RadixThemesComponent):
...
class TabsList(RadixThemesComponent):
+ def add_style(self): ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- size: Optional[Union[Var[Literal["1", "2"]], Literal["1", "2"]]] = None,
+ size: Optional[
+ Union[
+ Breakpoints[str, Literal["1", "2"]],
+ Literal["1", "2"],
+ Var[Union[Breakpoints[str, Literal["1", "2"]], Literal["1", "2"]]],
+ ]
+ ] = None,
+ loop: Optional[Union[Var[bool], bool]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "TabsList":
"""Create a new component instance.
@@ -175,6 +130,7 @@ class TabsList(RadixThemesComponent):
Args:
*children: Child components.
size: Tabs size "1" - "2"
+ loop: When true, the tabs will loop when reaching the end.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -198,63 +154,63 @@ class TabsTrigger(RadixThemesComponent):
disabled: Optional[Union[Var[bool], bool]] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
@@ -264,52 +220,22 @@ class TabsTrigger(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "TabsTrigger":
"""Create a TabsTrigger component.
@@ -331,65 +257,39 @@ class TabsTrigger(RadixThemesComponent):
"""
...
+ def add_style(self) -> Dict[str, Any] | None: ...
+
class TabsContent(RadixThemesComponent):
+ def add_style(self) -> dict[str, Any] | None: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
value: Optional[Union[Var[str], str]] = None,
+ force_mount: Optional[Union[Var[bool], bool]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "TabsContent":
"""Create a new component instance.
@@ -399,6 +299,7 @@ class TabsContent(RadixThemesComponent):
Args:
*children: Child components.
value: The value of the tab. Must be unique for each tab.
+ force_mount: Used to force mounting when more control is needed. Useful when controlling animation with React animation libraries.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -425,65 +326,37 @@ class Tabs(ComponentNamespace):
value: Optional[Union[Var[str], str]] = None,
orientation: Optional[
Union[
- Var[Literal["horizontal", "vertical"]],
Literal["horizontal", "vertical"],
+ Var[Literal["horizontal", "vertical"]],
]
] = None,
+ dir: Optional[Union[Literal["ltr", "rtl"], Var[Literal["ltr", "rtl"]]]] = None,
+ activation_mode: Optional[
+ Union[Literal["automatic", "manual"], Var[Literal["automatic", "manual"]]]
+ ] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_change: Optional[EventType[str]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "TabsRoot":
"""Create a new component instance.
@@ -495,6 +368,9 @@ class Tabs(ComponentNamespace):
default_value: The value of the tab that should be active when initially rendered. Use when you do not need to control the state of the tabs.
value: The controlled value of the tab that should be active. Use when you need to control the state of the tabs.
orientation: The orientation of the tabs.
+ dir: Reading direction of the tabs.
+ activation_mode: The mode of activation for the tabs. "automatic" will activate the tab when focused. "manual" will activate the tab when clicked.
+ on_change: Props to rename Fired when the value of the tabs changes.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
diff --git a/reflex/components/radix/themes/components/text_area.py b/reflex/components/radix/themes/components/text_area.py
index 2eec48631..9f006c2e3 100644
--- a/reflex/components/radix/themes/components/text_area.py
+++ b/reflex/components/radix/themes/components/text_area.py
@@ -1,34 +1,44 @@
"""Interactive components provided by @radix-ui/themes."""
-from typing import Any, Dict, Literal, Union
-from reflex import el
+from typing import Literal, Union
+
from reflex.components.component import Component
+from reflex.components.core.breakpoints import Responsive
from reflex.components.core.debounce import DebounceInput
-from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.components.el import elements
+from reflex.vars.base import Var
from ..base import (
LiteralAccentColor,
+ LiteralRadius,
RadixThemesComponent,
)
LiteralTextAreaSize = Literal["1", "2", "3"]
+LiteralTextAreaResize = Literal["none", "vertical", "horizontal", "both"]
-class TextArea(RadixThemesComponent, el.Textarea):
+
+class TextArea(RadixThemesComponent, elements.Textarea):
"""The input part of a TextArea, may be used by itself."""
tag = "TextArea"
# The size of the text area: "1" | "2" | "3"
- size: Var[LiteralTextAreaSize]
+ size: Var[Responsive[LiteralTextAreaSize]]
# The variant of the text area
variant: Var[Literal["classic", "surface", "soft"]]
+ # The resize behavior of the text area: "none" | "vertical" | "horizontal" | "both"
+ resize: Var[Responsive[LiteralTextAreaResize]]
+
# The color of the text area
color_scheme: Var[LiteralAccentColor]
+ # The radius of the text area: "none" | "small" | "medium" | "large" | "full"
+ radius: Var[LiteralRadius]
+
# Whether the form control should have autocomplete enabled
auto_complete: Var[bool]
@@ -82,25 +92,10 @@ class TextArea(RadixThemesComponent, el.Textarea):
Returns:
The component.
"""
- if props.get("value") is not None and props.get("on_change"):
+ if props.get("value") is not None and props.get("on_change") is not None:
# create a debounced input if the user requests full control to avoid typing jank
return DebounceInput.create(super().create(*children, **props))
return super().create(*children, **props)
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the event triggers that pass the component's value to the handler.
-
- Returns:
- A dict mapping the event trigger to the var that is passed to the handler.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_CHANGE: lambda e0: [e0.target.value],
- EventTriggers.ON_FOCUS: lambda e0: [e0.target.value],
- EventTriggers.ON_BLUR: lambda e0: [e0.target.value],
- EventTriggers.ON_KEY_DOWN: lambda e0: [e0.key],
- EventTriggers.ON_KEY_UP: lambda e0: [e0.key],
- }
-
text_area = TextArea.create
diff --git a/reflex/components/radix/themes/components/text_area.pyi b/reflex/components/radix/themes/components/text_area.pyi
index 48220be54..099a1700a 100644
--- a/reflex/components/radix/themes/components/text_area.pyi
+++ b/reflex/components/radix/themes/components/text_area.pyi
@@ -1,104 +1,131 @@
"""Stub file for reflex/components/radix/themes/components/text_area.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.components.el import elements
+from reflex.event import EventType
from reflex.style import Style
-from typing import Any, Dict, Literal, Union
-from reflex import el
-from reflex.components.component import Component
-from reflex.components.core.debounce import DebounceInput
-from reflex.constants import EventTriggers
-from reflex.vars import Var
-from ..base import LiteralAccentColor, RadixThemesComponent
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
LiteralTextAreaSize = Literal["1", "2", "3"]
+LiteralTextAreaResize = Literal["none", "vertical", "horizontal", "both"]
-class TextArea(RadixThemesComponent, el.Textarea):
+class TextArea(RadixThemesComponent, elements.Textarea):
@overload
@classmethod
def create( # type: ignore
cls,
*children,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
variant: Optional[
Union[
- Var[Literal["classic", "surface", "soft"]],
- Literal["classic", "surface", "soft"],
+ Literal["classic", "soft", "surface"],
+ Var[Literal["classic", "soft", "surface"]],
+ ]
+ ] = None,
+ resize: Optional[
+ Union[
+ Breakpoints[str, Literal["both", "horizontal", "none", "vertical"]],
+ Literal["both", "horizontal", "none", "vertical"],
+ Var[
+ Union[
+ Breakpoints[
+ str, Literal["both", "horizontal", "none", "vertical"]
+ ],
+ Literal["both", "horizontal", "none", "vertical"],
+ ]
+ ],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
+ ],
+ ]
+ ] = None,
+ radius: Optional[
+ Union[
+ Literal["full", "large", "medium", "none", "small"],
+ Var[Literal["full", "large", "medium", "none", "small"]],
]
] = None,
auto_complete: Optional[Union[Var[bool], bool]] = None,
auto_focus: Optional[Union[Var[bool], bool]] = None,
dirname: Optional[Union[Var[str], str]] = None,
disabled: Optional[Union[Var[bool], bool]] = None,
- form: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
+ form: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
max_length: Optional[Union[Var[int], int]] = None,
min_length: Optional[Union[Var[int], int]] = None,
name: Optional[Union[Var[str], str]] = None,
@@ -109,109 +136,57 @@ class TextArea(RadixThemesComponent, el.Textarea):
value: Optional[Union[Var[str], str]] = None,
wrap: Optional[Union[Var[str], str]] = None,
auto_height: Optional[Union[Var[bool], bool]] = None,
- cols: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
+ cols: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_submit: Optional[Union[Var[bool], bool]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_key_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_key_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[str]] = None,
+ on_change: Optional[EventType[str]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[str]] = None,
+ on_key_down: Optional[EventType[str]] = None,
+ on_key_up: Optional[EventType[str]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "TextArea":
"""Create an Input component.
@@ -219,7 +194,9 @@ class TextArea(RadixThemesComponent, el.Textarea):
*children: The children of the component.
size: The size of the text area: "1" | "2" | "3"
variant: The variant of the text area
+ resize: The resize behavior of the text area: "none" | "vertical" | "horizontal" | "both"
color_scheme: The color of the text area
+ radius: The radius of the text area: "none" | "small" | "medium" | "large" | "full"
auto_complete: Whether the form control should have autocomplete enabled
auto_focus: Automatically focuses the textarea when the page loads
dirname: Name part of the textarea to submit in 'dir' and 'name' pair when form is submitted
@@ -237,6 +214,11 @@ class TextArea(RadixThemesComponent, el.Textarea):
auto_height: Automatically fit the content height to the text (use min-height with this prop)
cols: Visible width of the text control, in average character widths
enter_key_submit: Enter key submits form (shift-enter adds new line)
+ on_change: Fired when the input value changes
+ on_focus: Fired when the input gains focus
+ on_blur: Fired when the input loses focus
+ on_key_down: Fired when a key is pressed down
+ on_key_up: Fired when a key is released
access_key: Provides a hint for generating a keyboard shortcut for the current element.
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
content_editable: Indicates whether the element's content is editable.
@@ -265,6 +247,5 @@ class TextArea(RadixThemesComponent, el.Textarea):
The component.
"""
...
- def get_event_triggers(self) -> Dict[str, Any]: ...
text_area = TextArea.create
diff --git a/reflex/components/radix/themes/components/text_field.py b/reflex/components/radix/themes/components/text_field.py
index 970b950e3..4277e93e0 100644
--- a/reflex/components/radix/themes/components/text_field.py
+++ b/reflex/components/radix/themes/components/text_field.py
@@ -1,16 +1,15 @@
"""Interactive components provided by @radix-ui/themes."""
+
from __future__ import annotations
-from typing import Any, Dict, Literal, Union
+from typing import Literal, Union
-from reflex.components import el
-from reflex.components.base.fragment import Fragment
from reflex.components.component import Component, ComponentNamespace
+from reflex.components.core.breakpoints import Responsive
from reflex.components.core.debounce import DebounceInput
-from reflex.constants import EventTriggers
-from reflex.style import Style, format_as_emotion
-from reflex.utils import console
-from reflex.vars import Var
+from reflex.components.el import elements
+from reflex.event import EventHandler, input_event, key_event
+from reflex.vars.base import Var
from ..base import (
LiteralAccentColor,
@@ -22,13 +21,13 @@ LiteralTextFieldSize = Literal["1", "2", "3"]
LiteralTextFieldVariant = Literal["classic", "surface", "soft"]
-class TextFieldRoot(el.Div, RadixThemesComponent):
+class TextFieldRoot(elements.Div, RadixThemesComponent):
"""Captures user input with an optional slot for buttons and icons."""
tag = "TextField.Root"
# Text field size "1" - "3"
- size: Var[LiteralTextFieldSize]
+ size: Var[Responsive[LiteralTextFieldSize]]
# Variant of text field: "classic" | "surface" | "soft"
variant: Var[LiteralTextFieldVariant]
@@ -72,6 +71,21 @@ class TextFieldRoot(el.Div, RadixThemesComponent):
# Value of the input
value: Var[Union[str, int, float]]
+ # Fired when the value of the textarea changes.
+ on_change: EventHandler[input_event]
+
+ # Fired when the textarea is focused.
+ on_focus: EventHandler[input_event]
+
+ # Fired when the textarea is blurred.
+ on_blur: EventHandler[input_event]
+
+ # Fired when a key is pressed down.
+ on_key_down: EventHandler[key_event]
+
+ # Fired when a key is released.
+ on_key_up: EventHandler[key_event]
+
@classmethod
def create(cls, *children, **props) -> Component:
"""Create an Input component.
@@ -84,100 +98,11 @@ class TextFieldRoot(el.Div, RadixThemesComponent):
The component.
"""
component = super().create(*children, **props)
- if props.get("value") is not None and props.get("on_change"):
+ if props.get("value") is not None and props.get("on_change") is not None:
# create a debounced input if the user requests full control to avoid typing jank
return DebounceInput.create(component)
return component
- @classmethod
- def create_root_deprecated(cls, *children, **props) -> Component:
- """Create a Fragment component (wrapper for deprecated name).
-
- Copy the attributes that were previously defined on TextFieldRoot in 0.4.9 to
- any child input elements (via custom_attrs).
-
- Args:
- *children: The children of the component.
- **props: The properties of the component.
-
- Returns:
- The component.
- """
- console.deprecate(
- feature_name="rx.input.root",
- reason="use rx.input without the .root suffix",
- deprecation_version="0.5.0",
- removal_version="0.6.0",
- )
- inputs = [
- child
- for child in children
- if isinstance(child, (TextFieldRoot, DebounceInput))
- ]
- if not inputs:
- # Old-style where no explicit child input was provided
- return cls.create(*children, **props)
- slots = [child for child in children if isinstance(child, TextFieldSlot)]
- carry_props = {
- prop: props.pop(prop)
- for prop in ["size", "variant", "color_scheme", "radius"]
- if prop in props
- }
- template = cls.create(**props)
- for child in inputs:
- child.children.extend(slots)
- custom_attrs = child.custom_attrs
- custom_attrs.update(
- {
- prop: value
- for prop, value in carry_props.items()
- if prop not in custom_attrs and getattr(child, prop) is None
- }
- )
- style = Style(template.style)
- style.update(child.style)
- child._get_style = lambda style=style: {
- "css": Var.create(format_as_emotion(style))
- }
- for trigger in template.event_triggers:
- if trigger not in child.event_triggers:
- child.event_triggers[trigger] = template.event_triggers[trigger]
- return Fragment.create(*inputs)
-
- @classmethod
- def create_input_deprecated(cls, *children, **props) -> Component:
- """Create a TextFieldRoot component (wrapper for deprecated name).
-
- Args:
- *children: The children of the component.
- **props: The properties of the component.
-
- Returns:
- The component.
- """
- console.deprecate(
- feature_name="rx.input.input",
- reason="use rx.input without the .input suffix",
- deprecation_version="0.5.0",
- removal_version="0.6.0",
- )
- return cls.create(*children, **props)
-
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the event triggers that pass the component's value to the handler.
-
- Returns:
- A dict mapping the event trigger to the var that is passed to the handler.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_CHANGE: lambda e0: [e0.target.value],
- EventTriggers.ON_FOCUS: lambda e0: [e0.target.value],
- EventTriggers.ON_BLUR: lambda e0: [e0.target.value],
- EventTriggers.ON_KEY_DOWN: lambda e0: [e0.key],
- EventTriggers.ON_KEY_UP: lambda e0: [e0.key],
- }
-
class TextFieldSlot(RadixThemesComponent):
"""Contains icons or buttons associated with an Input."""
@@ -191,10 +116,8 @@ class TextFieldSlot(RadixThemesComponent):
class TextField(ComponentNamespace):
"""TextField components namespace."""
- root = staticmethod(TextFieldRoot.create_root_deprecated)
- input = staticmethod(TextFieldRoot.create_input_deprecated)
slot = staticmethod(TextFieldSlot.create)
__call__ = staticmethod(TextFieldRoot.create)
-text_field = TextField()
+input = text_field = TextField()
diff --git a/reflex/components/radix/themes/components/text_field.pyi b/reflex/components/radix/themes/components/text_field.pyi
index c14fb031a..ffe827aff 100644
--- a/reflex/components/radix/themes/components/text_field.pyi
+++ b/reflex/components/radix/themes/components/text_field.pyi
@@ -1,107 +1,111 @@
"""Stub file for reflex/components/radix/themes/components/text_field.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+
+from reflex.components.component import ComponentNamespace
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.components.el import elements
+from reflex.event import EventType
from reflex.style import Style
-from typing import Any, Dict, Literal, Union
-from reflex.components import el
-from reflex.components.base.fragment import Fragment
-from reflex.components.component import Component, ComponentNamespace
-from reflex.components.core.debounce import DebounceInput
-from reflex.constants import EventTriggers
-from reflex.style import Style, format_as_emotion
-from reflex.utils import console
-from reflex.vars import Var
-from ..base import LiteralAccentColor, LiteralRadius, RadixThemesComponent
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
LiteralTextFieldSize = Literal["1", "2", "3"]
LiteralTextFieldVariant = Literal["classic", "surface", "soft"]
-class TextFieldRoot(el.Div, RadixThemesComponent):
+class TextFieldRoot(elements.Div, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
cls,
*children,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
variant: Optional[
Union[
- Var[Literal["classic", "surface", "soft"]],
- Literal["classic", "surface", "soft"],
+ Literal["classic", "soft", "surface"],
+ Var[Literal["classic", "soft", "surface"]],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
radius: Optional[
Union[
- Var[Literal["none", "small", "medium", "large", "full"]],
- Literal["none", "small", "medium", "large", "full"],
+ Literal["full", "large", "medium", "none", "small"],
+ Var[Literal["full", "large", "medium", "none", "small"]],
]
] = None,
auto_complete: Optional[Union[Var[bool], bool]] = None,
@@ -114,110 +118,56 @@ class TextFieldRoot(el.Div, RadixThemesComponent):
read_only: Optional[Union[Var[bool], bool]] = None,
required: Optional[Union[Var[bool], bool]] = None,
type: Optional[Union[Var[str], str]] = None,
- value: Optional[
- Union[Var[Union[str, int, float]], Union[str, int, float]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ value: Optional[Union[Var[Union[float, int, str]], float, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_key_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_key_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[str]] = None,
+ on_change: Optional[EventType[str]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[str]] = None,
+ on_key_down: Optional[EventType[str]] = None,
+ on_key_up: Optional[EventType[str]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "TextFieldRoot":
"""Create an Input component.
@@ -238,6 +188,11 @@ class TextFieldRoot(el.Div, RadixThemesComponent):
required: Indicates that the input is required
type: Specifies the type of input
value: Value of the input
+ on_change: Fired when the value of the textarea changes.
+ on_focus: Fired when the textarea is focused.
+ on_blur: Fired when the textarea is blurred.
+ on_key_down: Fired when a key is pressed down.
+ on_key_up: Fired when a key is released.
access_key: Provides a hint for generating a keyboard shortcut for the current element.
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
content_editable: Indicates whether the element's content is editable.
@@ -266,11 +221,6 @@ class TextFieldRoot(el.Div, RadixThemesComponent):
The component.
"""
...
- @classmethod
- def create_root_deprecated(cls, *children, **props) -> Component: ...
- @classmethod
- def create_input_deprecated(cls, *children, **props) -> Component: ...
- def get_event_triggers(self) -> Dict[str, Any]: ...
class TextFieldSlot(RadixThemesComponent):
@overload
@@ -280,63 +230,63 @@ class TextFieldSlot(RadixThemesComponent):
*children,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
@@ -346,52 +296,22 @@ class TextFieldSlot(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "TextFieldSlot":
"""Create a new component instance.
@@ -415,88 +335,94 @@ class TextFieldSlot(RadixThemesComponent):
...
class TextField(ComponentNamespace):
- root = staticmethod(TextFieldRoot.create_root_deprecated)
- input = staticmethod(TextFieldRoot.create_input_deprecated)
slot = staticmethod(TextFieldSlot.create)
@staticmethod
def __call__(
*children,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
variant: Optional[
Union[
- Var[Literal["classic", "surface", "soft"]],
- Literal["classic", "surface", "soft"],
+ Literal["classic", "soft", "surface"],
+ Var[Literal["classic", "soft", "surface"]],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
radius: Optional[
Union[
- Var[Literal["none", "small", "medium", "large", "full"]],
- Literal["none", "small", "medium", "large", "full"],
+ Literal["full", "large", "medium", "none", "small"],
+ Var[Literal["full", "large", "medium", "none", "small"]],
]
] = None,
auto_complete: Optional[Union[Var[bool], bool]] = None,
@@ -509,110 +435,56 @@ class TextField(ComponentNamespace):
read_only: Optional[Union[Var[bool], bool]] = None,
required: Optional[Union[Var[bool], bool]] = None,
type: Optional[Union[Var[str], str]] = None,
- value: Optional[
- Union[Var[Union[str, int, float]], Union[str, int, float]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ value: Optional[Union[Var[Union[float, int, str]], float, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_key_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_key_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[str]] = None,
+ on_change: Optional[EventType[str]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[str]] = None,
+ on_key_down: Optional[EventType[str]] = None,
+ on_key_up: Optional[EventType[str]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "TextFieldRoot":
"""Create an Input component.
@@ -633,6 +505,11 @@ class TextField(ComponentNamespace):
required: Indicates that the input is required
type: Specifies the type of input
value: Value of the input
+ on_change: Fired when the value of the textarea changes.
+ on_focus: Fired when the textarea is focused.
+ on_blur: Fired when the textarea is blurred.
+ on_key_down: Fired when a key is pressed down.
+ on_key_up: Fired when a key is released.
access_key: Provides a hint for generating a keyboard shortcut for the current element.
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
content_editable: Indicates whether the element's content is editable.
@@ -662,4 +539,4 @@ class TextField(ComponentNamespace):
"""
...
-text_field = TextField()
+input = text_field = TextField()
diff --git a/reflex/components/radix/themes/components/tooltip.py b/reflex/components/radix/themes/components/tooltip.py
index 29bac80d0..ac35c86d1 100644
--- a/reflex/components/radix/themes/components/tooltip.py
+++ b/reflex/components/radix/themes/components/tooltip.py
@@ -1,10 +1,11 @@
"""Interactive components provided by @radix-ui/themes."""
-from typing import Any, Dict, Literal, Union
+
+from typing import Dict, Literal, Union
from reflex.components.component import Component
-from reflex.constants import EventTriggers
+from reflex.event import EventHandler, empty_event, identity_event
from reflex.utils import format
-from reflex.vars import Var
+from reflex.vars.base import Var
from ..base import (
RadixThemesComponent,
@@ -83,18 +84,14 @@ class Tooltip(RadixThemesComponent):
# By default, screenreaders will announce the content inside the component. If this is not descriptive enough, or you have content that cannot be announced, use aria-label as a more descriptive label.
aria_label: Var[str]
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
+ # Fired when the open state changes.
+ on_open_change: EventHandler[identity_event(bool)]
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- EventTriggers.ON_OPEN_CHANGE: lambda e0: [e0.target.value],
- EventTriggers.ON_ESCAPE_KEY_DOWN: lambda e0: [e0.target.value],
- EventTriggers.ON_POINTER_DOWN_OUTSIDE: lambda e0: [e0.target.value],
- }
+ # Fired when the escape key is pressed.
+ on_escape_key_down: EventHandler[empty_event]
+
+ # Fired when the pointer is down outside the tooltip.
+ on_pointer_down_outside: EventHandler[empty_event]
@classmethod
def create(cls, *children, **props) -> Component:
diff --git a/reflex/components/radix/themes/components/tooltip.pyi b/reflex/components/radix/themes/components/tooltip.pyi
index b9c0feca6..42875e1e5 100644
--- a/reflex/components/radix/themes/components/tooltip.pyi
+++ b/reflex/components/radix/themes/components/tooltip.pyi
@@ -1,17 +1,16 @@
"""Stub file for reflex/components/radix/themes/components/tooltip.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+
+from reflex.event import (
+ EventType,
+)
from reflex.style import Style
-from typing import Any, Dict, Literal, Union
-from reflex.components.component import Component
-from reflex.constants import EventTriggers
-from reflex.utils import format
-from reflex.vars import Var
+from reflex.vars.base import Var
+
from ..base import RadixThemesComponent
LiteralSideType = Literal["top", "right", "bottom", "left"]
@@ -19,7 +18,6 @@ LiteralAlignType = Literal["start", "center", "end"]
LiteralStickyType = Literal["partial", "always"]
class Tooltip(RadixThemesComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
@overload
@classmethod
def create( # type: ignore
@@ -30,35 +28,33 @@ class Tooltip(RadixThemesComponent):
open: Optional[Union[Var[bool], bool]] = None,
side: Optional[
Union[
- Var[Literal["top", "right", "bottom", "left"]],
- Literal["top", "right", "bottom", "left"],
+ Literal["bottom", "left", "right", "top"],
+ Var[Literal["bottom", "left", "right", "top"]],
]
] = None,
- side_offset: Optional[Union[Var[Union[float, int]], Union[float, int]]] = None,
+ side_offset: Optional[Union[Var[Union[float, int]], float, int]] = None,
align: Optional[
Union[
- Var[Literal["start", "center", "end"]],
- Literal["start", "center", "end"],
+ Literal["center", "end", "start"],
+ Var[Literal["center", "end", "start"]],
]
] = None,
- align_offset: Optional[Union[Var[Union[float, int]], Union[float, int]]] = None,
+ align_offset: Optional[Union[Var[Union[float, int]], float, int]] = None,
avoid_collisions: Optional[Union[Var[bool], bool]] = None,
collision_padding: Optional[
Union[
- Var[Union[float, int, Dict[str, Union[float, int]]]],
- Union[float, int, Dict[str, Union[float, int]]],
+ Dict[str, Union[float, int]],
+ Var[Union[Dict[str, Union[float, int]], float, int]],
+ float,
+ int,
]
] = None,
- arrow_padding: Optional[
- Union[Var[Union[float, int]], Union[float, int]]
- ] = None,
+ arrow_padding: Optional[Union[Var[Union[float, int]], float, int]] = None,
sticky: Optional[
- Union[Var[Literal["partial", "always"]], Literal["partial", "always"]]
+ Union[Literal["always", "partial"], Var[Literal["always", "partial"]]]
] = None,
hide_when_detached: Optional[Union[Var[bool], bool]] = None,
- delay_duration: Optional[
- Union[Var[Union[float, int]], Union[float, int]]
- ] = None,
+ delay_duration: Optional[Union[Var[Union[float, int]], float, int]] = None,
disable_hoverable_content: Optional[Union[Var[bool], bool]] = None,
force_mount: Optional[Union[Var[bool], bool]] = None,
aria_label: Optional[Union[Var[str], str]] = None,
@@ -68,61 +64,25 @@ class Tooltip(RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_escape_key_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_open_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_pointer_down_outside: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_escape_key_down: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_open_change: Optional[EventType[bool]] = None,
+ on_pointer_down_outside: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Tooltip":
"""Initialize the Tooltip component.
@@ -146,6 +106,9 @@ class Tooltip(RadixThemesComponent):
disable_hoverable_content: Prevents Tooltip content from remaining open when hovering.
force_mount: Used to force mounting when more control is needed. Useful when controlling animation with React animation libraries.
aria_label: By default, screenreaders will announce the content inside the component. If this is not descriptive enough, or you have content that cannot be announced, use aria-label as a more descriptive label.
+ on_open_change: Fired when the open state changes.
+ on_escape_key_down: Fired when the escape key is pressed.
+ on_pointer_down_outside: Fired when the pointer is down outside the tooltip.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
diff --git a/reflex/components/radix/themes/layout/__init__.py b/reflex/components/radix/themes/layout/__init__.py
index 4832c60db..b141146bd 100644
--- a/reflex/components/radix/themes/layout/__init__.py
+++ b/reflex/components/radix/themes/layout/__init__.py
@@ -1,42 +1,17 @@
"""Layout components."""
-from .box import Box
-from .center import Center
-from .container import Container
-from .flex import Flex
-from .grid import Grid
-from .list import list_ns as list
-from .section import Section
-from .spacer import Spacer
-from .stack import HStack, Stack, VStack
+from __future__ import annotations
-box = Box.create
-center = Center.create
-container = Container.create
-flex = Flex.create
-grid = Grid.create
-section = Section.create
-spacer = Spacer.create
-stack = Stack.create
-hstack = HStack.create
-vstack = VStack.create
-list_item = list.item
-ordered_list = list.ordered
-unordered_list = list.unordered
+from reflex import RADIX_THEMES_LAYOUT_MAPPING
+from reflex.utils import lazy_loader
-__all__ = [
- "box",
- "center",
- "container",
- "flex",
- "grid",
- "section",
- "spacer",
- "stack",
- "hstack",
- "vstack",
- "list",
- "list_item",
- "ordered_list",
- "unordered_list",
-]
+_SUBMOD_ATTRS: dict[str, list[str]] = {
+ "".join(k.split("components.radix.themes.layout.")[-1]): v
+ for k, v in RADIX_THEMES_LAYOUT_MAPPING.items()
+}
+
+
+__getattr__, __dir__, __all__ = lazy_loader.attach(
+ __name__,
+ submod_attrs=_SUBMOD_ATTRS,
+)
diff --git a/reflex/components/radix/themes/layout/__init__.pyi b/reflex/components/radix/themes/layout/__init__.pyi
new file mode 100644
index 000000000..6712a3068
--- /dev/null
+++ b/reflex/components/radix/themes/layout/__init__.pyi
@@ -0,0 +1,19 @@
+"""Stub file for reflex/components/radix/themes/layout/__init__.py"""
+# ------------------- DO NOT EDIT ----------------------
+# This file was generated by `reflex/utils/pyi_generator.py`!
+# ------------------------------------------------------
+
+from .box import box as box
+from .center import center as center
+from .container import container as container
+from .flex import flex as flex
+from .grid import grid as grid
+from .list import list_item as list_item
+from .list import list_ns as list # noqa
+from .list import ordered_list as ordered_list
+from .list import unordered_list as unordered_list
+from .section import section as section
+from .spacer import spacer as spacer
+from .stack import hstack as hstack
+from .stack import stack as stack
+from .stack import vstack as vstack
diff --git a/reflex/components/radix/themes/layout/base.py b/reflex/components/radix/themes/layout/base.py
index 6e202a8c8..3ee78d209 100644
--- a/reflex/components/radix/themes/layout/base.py
+++ b/reflex/components/radix/themes/layout/base.py
@@ -4,7 +4,8 @@ from __future__ import annotations
from typing import Literal
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.vars.base import Var
from ..base import (
CommonMarginProps,
@@ -22,28 +23,28 @@ class LayoutComponent(CommonMarginProps, RadixThemesComponent):
"""
# Padding: "0" - "9"
- p: Var[LiteralSpacing]
+ p: Var[Responsive[LiteralSpacing]]
# Padding horizontal: "0" - "9"
- px: Var[LiteralSpacing]
+ px: Var[Responsive[LiteralSpacing]]
# Padding vertical: "0" - "9"
- py: Var[LiteralSpacing]
+ py: Var[Responsive[LiteralSpacing]]
# Padding top: "0" - "9"
- pt: Var[LiteralSpacing]
+ pt: Var[Responsive[LiteralSpacing]]
# Padding right: "0" - "9"
- pr: Var[LiteralSpacing]
+ pr: Var[Responsive[LiteralSpacing]]
# Padding bottom: "0" - "9"
- pb: Var[LiteralSpacing]
+ pb: Var[Responsive[LiteralSpacing]]
# Padding left: "0" - "9"
- pl: Var[LiteralSpacing]
+ pl: Var[Responsive[LiteralSpacing]]
# Whether the element will take up the smallest possible space: "0" | "1"
- flex_shrink: Var[LiteralBoolNumber]
+ flex_shrink: Var[Responsive[LiteralBoolNumber]]
# Whether the element will take up the largest possible space: "0" | "1"
- flex_grow: Var[LiteralBoolNumber]
+ flex_grow: Var[Responsive[LiteralBoolNumber]]
diff --git a/reflex/components/radix/themes/layout/base.pyi b/reflex/components/radix/themes/layout/base.pyi
index 31310928e..df51b07f9 100644
--- a/reflex/components/radix/themes/layout/base.pyi
+++ b/reflex/components/radix/themes/layout/base.pyi
@@ -1,15 +1,16 @@
"""Stub file for reflex/components/radix/themes/layout/base.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.event import EventType
from reflex.style import Style
-from typing import Literal
-from reflex.vars import Var
-from ..base import CommonMarginProps, LiteralSpacing, RadixThemesComponent
+from reflex.vars.base import Var
+
+from ..base import CommonMarginProps, RadixThemesComponent
LiteralBoolNumber = Literal["0", "1"]
@@ -21,88 +22,177 @@ class LayoutComponent(CommonMarginProps, RadixThemesComponent):
*children,
p: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[
+ str, Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
+ ],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ],
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ]
+ ],
]
] = None,
px: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[
+ str, Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
+ ],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ],
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ]
+ ],
]
] = None,
py: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[
+ str, Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
+ ],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ],
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ]
+ ],
]
] = None,
pt: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[
+ str, Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
+ ],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ],
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ]
+ ],
]
] = None,
pr: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[
+ str, Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
+ ],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ],
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ]
+ ],
]
] = None,
pb: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[
+ str, Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
+ ],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ],
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ]
+ ],
]
] = None,
pl: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[
+ str, Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
+ ],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ],
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ]
+ ],
+ ]
+ ] = None,
+ flex_shrink: Optional[
+ Union[
+ Breakpoints[str, Literal["0", "1"]],
+ Literal["0", "1"],
+ Var[Union[Breakpoints[str, Literal["0", "1"]], Literal["0", "1"]]],
+ ]
+ ] = None,
+ flex_grow: Optional[
+ Union[
+ Breakpoints[str, Literal["0", "1"]],
+ Literal["0", "1"],
+ Var[Union[Breakpoints[str, Literal["0", "1"]], Literal["0", "1"]]],
]
] = None,
- flex_shrink: Optional[Union[Var[Literal["0", "1"]], Literal["0", "1"]]] = None,
- flex_grow: Optional[Union[Var[Literal["0", "1"]], Literal["0", "1"]]] = None,
m: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
]
] = None,
mx: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
]
] = None,
my: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
]
] = None,
mt: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
]
] = None,
mr: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
]
] = None,
mb: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
]
] = None,
ml: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
]
] = None,
style: Optional[Style] = None,
@@ -111,52 +201,22 @@ class LayoutComponent(CommonMarginProps, RadixThemesComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "LayoutComponent":
"""Create a new component instance.
diff --git a/reflex/components/radix/themes/layout/box.py b/reflex/components/radix/themes/layout/box.py
index b9bb99107..a8ace5956 100644
--- a/reflex/components/radix/themes/layout/box.py
+++ b/reflex/components/radix/themes/layout/box.py
@@ -1,12 +1,16 @@
"""Declarative layout and common spacing props."""
+
from __future__ import annotations
-from reflex import el
+from reflex.components.el import elements
from ..base import RadixThemesComponent
-class Box(el.Div, RadixThemesComponent):
+class Box(elements.Div, RadixThemesComponent):
"""A fundamental layout building block, based on `div` element."""
tag = "Box"
+
+
+box = Box.create
diff --git a/reflex/components/radix/themes/layout/box.pyi b/reflex/components/radix/themes/layout/box.pyi
index 323a88540..895725a35 100644
--- a/reflex/components/radix/themes/layout/box.pyi
+++ b/reflex/components/radix/themes/layout/box.pyi
@@ -1,113 +1,69 @@
"""Stub file for reflex/components/radix/themes/layout/box.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+from reflex.components.el import elements
+from reflex.event import EventType
from reflex.style import Style
-from reflex import el
+from reflex.vars.base import Var
+
from ..base import RadixThemesComponent
-class Box(el.Div, RadixThemesComponent):
+class Box(elements.Div, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Box":
"""Create a new component instance.
@@ -144,3 +100,5 @@ class Box(el.Div, RadixThemesComponent):
A new component instance.
"""
...
+
+box = Box.create
diff --git a/reflex/components/radix/themes/layout/center.py b/reflex/components/radix/themes/layout/center.py
index 16441876a..3ac4fecb1 100644
--- a/reflex/components/radix/themes/layout/center.py
+++ b/reflex/components/radix/themes/layout/center.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from reflex.style import Style
+from typing import Any
from .flex import Flex
@@ -10,16 +10,17 @@ from .flex import Flex
class Center(Flex):
"""A center component."""
- def add_style(self) -> Style | None:
+ def add_style(self) -> dict[str, Any] | None:
"""Add style that center the content.
Returns:
The style of the component.
"""
- return Style(
- {
- "display": "flex",
- "align_items": "center",
- "justify_content": "center",
- }
- )
+ return {
+ "display": "flex",
+ "align_items": "center",
+ "justify_content": "center",
+ }
+
+
+center = Center.create
diff --git a/reflex/components/radix/themes/layout/center.pyi b/reflex/components/radix/themes/layout/center.pyi
index 0fd45f940..eb976892e 100644
--- a/reflex/components/radix/themes/layout/center.pyi
+++ b/reflex/components/radix/themes/layout/center.pyi
@@ -1,17 +1,19 @@
"""Stub file for reflex/components/radix/themes/layout/center.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
+
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.event import EventType
from reflex.style import Style
+from reflex.vars.base import Var
+
from .flex import Flex
class Center(Flex):
- def add_style(self) -> Style | None: ...
+ def add_style(self) -> dict[str, Any] | None: ...
@overload
@classmethod
def create( # type: ignore
@@ -20,126 +22,125 @@ class Center(Flex):
as_child: Optional[Union[Var[bool], bool]] = None,
direction: Optional[
Union[
- Var[Literal["row", "column", "row-reverse", "column-reverse"]],
- Literal["row", "column", "row-reverse", "column-reverse"],
+ Breakpoints[
+ str, Literal["column", "column-reverse", "row", "row-reverse"]
+ ],
+ Literal["column", "column-reverse", "row", "row-reverse"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Literal["column", "column-reverse", "row", "row-reverse"],
+ ],
+ Literal["column", "column-reverse", "row", "row-reverse"],
+ ]
+ ],
]
] = None,
align: Optional[
Union[
- Var[Literal["start", "center", "end", "baseline", "stretch"]],
- Literal["start", "center", "end", "baseline", "stretch"],
+ Breakpoints[
+ str, Literal["baseline", "center", "end", "start", "stretch"]
+ ],
+ Literal["baseline", "center", "end", "start", "stretch"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Literal["baseline", "center", "end", "start", "stretch"],
+ ],
+ Literal["baseline", "center", "end", "start", "stretch"],
+ ]
+ ],
]
] = None,
justify: Optional[
Union[
- Var[Literal["start", "center", "end", "between"]],
- Literal["start", "center", "end", "between"],
+ Breakpoints[str, Literal["between", "center", "end", "start"]],
+ Literal["between", "center", "end", "start"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["between", "center", "end", "start"]],
+ Literal["between", "center", "end", "start"],
+ ]
+ ],
]
] = None,
wrap: Optional[
Union[
- Var[Literal["nowrap", "wrap", "wrap-reverse"]],
+ Breakpoints[str, Literal["nowrap", "wrap", "wrap-reverse"]],
Literal["nowrap", "wrap", "wrap-reverse"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["nowrap", "wrap", "wrap-reverse"]],
+ Literal["nowrap", "wrap", "wrap-reverse"],
+ ]
+ ],
]
] = None,
spacing: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[
+ str, Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
+ ],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ],
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ]
+ ],
]
] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Center":
"""Create a new component instance.
@@ -182,3 +183,5 @@ class Center(Flex):
A new component instance.
"""
...
+
+center = Center.create
diff --git a/reflex/components/radix/themes/layout/container.py b/reflex/components/radix/themes/layout/container.py
index 2ab548cdf..b1d2fbed3 100644
--- a/reflex/components/radix/themes/layout/container.py
+++ b/reflex/components/radix/themes/layout/container.py
@@ -1,18 +1,20 @@
"""Declarative layout and common spacing props."""
+
from __future__ import annotations
from typing import Literal
-from reflex import el
+from reflex.components.core.breakpoints import Responsive
+from reflex.components.el import elements
from reflex.style import STACK_CHILDREN_FULL_WIDTH
-from reflex.vars import Var
+from reflex.vars.base import LiteralVar, Var
from ..base import RadixThemesComponent
LiteralContainerSize = Literal["1", "2", "3", "4"]
-class Container(el.Div, RadixThemesComponent):
+class Container(elements.Div, RadixThemesComponent):
"""Constrains the maximum width of page content.
See https://www.radix-ui.com/themes/docs/components/container
@@ -21,7 +23,7 @@ class Container(el.Div, RadixThemesComponent):
tag = "Container"
# The size of the container: "1" - "4" (default "3")
- size: Var[LiteralContainerSize] = Var.create_safe("3")
+ size: Var[Responsive[LiteralContainerSize]] = LiteralVar.create("3")
@classmethod
def create(
@@ -49,3 +51,6 @@ class Container(el.Div, RadixThemesComponent):
padding=padding,
**props,
)
+
+
+container = Container.create
diff --git a/reflex/components/radix/themes/layout/container.pyi b/reflex/components/radix/themes/layout/container.pyi
index a2ea0266f..a5e50b9f3 100644
--- a/reflex/components/radix/themes/layout/container.pyi
+++ b/reflex/components/radix/themes/layout/container.pyi
@@ -1,21 +1,21 @@
"""Stub file for reflex/components/radix/themes/layout/container.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.components.el import elements
+from reflex.event import EventType
from reflex.style import Style
-from typing import Literal
-from reflex import el
-from reflex.style import STACK_CHILDREN_FULL_WIDTH
-from reflex.vars import Var
+from reflex.vars.base import Var
+
from ..base import RadixThemesComponent
LiteralContainerSize = Literal["1", "2", "3", "4"]
-class Container(el.Div, RadixThemesComponent):
+class Container(elements.Div, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
@@ -24,100 +24,63 @@ class Container(el.Div, RadixThemesComponent):
padding: Optional[str] = "16px",
stack_children_full_width: Optional[bool] = False,
size: Optional[
- Union[Var[Literal["1", "2", "3", "4"]], Literal["1", "2", "3", "4"]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3", "4"]],
+ Literal["1", "2", "3", "4"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3", "4"]],
+ Literal["1", "2", "3", "4"],
+ ]
+ ],
+ ]
] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Container":
"""Create the container component.
@@ -131,3 +94,5 @@ class Container(el.Div, RadixThemesComponent):
The container component.
"""
...
+
+container = Container.create
diff --git a/reflex/components/radix/themes/layout/flex.py b/reflex/components/radix/themes/layout/flex.py
index ef7aed16c..8be16973d 100644
--- a/reflex/components/radix/themes/layout/flex.py
+++ b/reflex/components/radix/themes/layout/flex.py
@@ -4,8 +4,9 @@ from __future__ import annotations
from typing import Dict, Literal
-from reflex import el
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.components.el import elements
+from reflex.vars.base import Var
from ..base import (
LiteralAlign,
@@ -18,7 +19,7 @@ LiteralFlexDirection = Literal["row", "column", "row-reverse", "column-reverse"]
LiteralFlexWrap = Literal["nowrap", "wrap", "wrap-reverse"]
-class Flex(el.Div, RadixThemesComponent):
+class Flex(elements.Div, RadixThemesComponent):
"""Component for creating flex layouts."""
tag = "Flex"
@@ -27,19 +28,22 @@ class Flex(el.Div, RadixThemesComponent):
as_child: Var[bool]
# How child items are layed out: "row" | "column" | "row-reverse" | "column-reverse"
- direction: Var[LiteralFlexDirection]
+ direction: Var[Responsive[LiteralFlexDirection]]
# Alignment of children along the main axis: "start" | "center" | "end" | "baseline" | "stretch"
- align: Var[LiteralAlign]
+ align: Var[Responsive[LiteralAlign]]
# Alignment of children along the cross axis: "start" | "center" | "end" | "between"
- justify: Var[LiteralJustify]
+ justify: Var[Responsive[LiteralJustify]]
# Whether children should wrap when they reach the end of their container: "nowrap" | "wrap" | "wrap-reverse"
- wrap: Var[LiteralFlexWrap]
+ wrap: Var[Responsive[LiteralFlexWrap]]
# Gap between children: "0" - "9"
- spacing: Var[LiteralSpacing]
+ spacing: Var[Responsive[LiteralSpacing]]
# Reflex maps the "spacing" prop to "gap" prop.
_rename_props: Dict[str, str] = {"spacing": "gap"}
+
+
+flex = Flex.create
diff --git a/reflex/components/radix/themes/layout/flex.pyi b/reflex/components/radix/themes/layout/flex.pyi
index 115e1d1ae..aba864f4f 100644
--- a/reflex/components/radix/themes/layout/flex.pyi
+++ b/reflex/components/radix/themes/layout/flex.pyi
@@ -1,21 +1,22 @@
"""Stub file for reflex/components/radix/themes/layout/flex.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.components.el import elements
+from reflex.event import EventType
from reflex.style import Style
-from typing import Dict, Literal
-from reflex import el
-from reflex.vars import Var
-from ..base import LiteralAlign, LiteralJustify, LiteralSpacing, RadixThemesComponent
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
LiteralFlexDirection = Literal["row", "column", "row-reverse", "column-reverse"]
LiteralFlexWrap = Literal["nowrap", "wrap", "wrap-reverse"]
-class Flex(el.Div, RadixThemesComponent):
+class Flex(elements.Div, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
@@ -24,126 +25,125 @@ class Flex(el.Div, RadixThemesComponent):
as_child: Optional[Union[Var[bool], bool]] = None,
direction: Optional[
Union[
- Var[Literal["row", "column", "row-reverse", "column-reverse"]],
- Literal["row", "column", "row-reverse", "column-reverse"],
+ Breakpoints[
+ str, Literal["column", "column-reverse", "row", "row-reverse"]
+ ],
+ Literal["column", "column-reverse", "row", "row-reverse"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Literal["column", "column-reverse", "row", "row-reverse"],
+ ],
+ Literal["column", "column-reverse", "row", "row-reverse"],
+ ]
+ ],
]
] = None,
align: Optional[
Union[
- Var[Literal["start", "center", "end", "baseline", "stretch"]],
- Literal["start", "center", "end", "baseline", "stretch"],
+ Breakpoints[
+ str, Literal["baseline", "center", "end", "start", "stretch"]
+ ],
+ Literal["baseline", "center", "end", "start", "stretch"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Literal["baseline", "center", "end", "start", "stretch"],
+ ],
+ Literal["baseline", "center", "end", "start", "stretch"],
+ ]
+ ],
]
] = None,
justify: Optional[
Union[
- Var[Literal["start", "center", "end", "between"]],
- Literal["start", "center", "end", "between"],
+ Breakpoints[str, Literal["between", "center", "end", "start"]],
+ Literal["between", "center", "end", "start"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["between", "center", "end", "start"]],
+ Literal["between", "center", "end", "start"],
+ ]
+ ],
]
] = None,
wrap: Optional[
Union[
- Var[Literal["nowrap", "wrap", "wrap-reverse"]],
+ Breakpoints[str, Literal["nowrap", "wrap", "wrap-reverse"]],
Literal["nowrap", "wrap", "wrap-reverse"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["nowrap", "wrap", "wrap-reverse"]],
+ Literal["nowrap", "wrap", "wrap-reverse"],
+ ]
+ ],
]
] = None,
spacing: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[
+ str, Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
+ ],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ],
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ]
+ ],
]
] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Flex":
"""Create a new component instance.
@@ -186,3 +186,5 @@ class Flex(el.Div, RadixThemesComponent):
A new component instance.
"""
...
+
+flex = Flex.create
diff --git a/reflex/components/radix/themes/layout/grid.py b/reflex/components/radix/themes/layout/grid.py
index 565703643..b9ac28d41 100644
--- a/reflex/components/radix/themes/layout/grid.py
+++ b/reflex/components/radix/themes/layout/grid.py
@@ -4,8 +4,9 @@ from __future__ import annotations
from typing import Dict, Literal
-from reflex import el
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.components.el import elements
+from reflex.vars.base import Var
from ..base import (
LiteralAlign,
@@ -17,7 +18,7 @@ from ..base import (
LiteralGridFlow = Literal["row", "column", "dense", "row-dense", "column-dense"]
-class Grid(el.Div, RadixThemesComponent):
+class Grid(elements.Div, RadixThemesComponent):
"""Component for creating grid layouts."""
tag = "Grid"
@@ -26,28 +27,28 @@ class Grid(el.Div, RadixThemesComponent):
as_child: Var[bool]
# Number of columns
- columns: Var[str]
+ columns: Var[Responsive[str]]
# Number of rows
- rows: Var[str]
+ rows: Var[Responsive[str]]
# How the grid items are layed out: "row" | "column" | "dense" | "row-dense" | "column-dense"
- flow: Var[LiteralGridFlow]
+ flow: Var[Responsive[LiteralGridFlow]]
# Alignment of children along the main axis: "start" | "center" | "end" | "baseline" | "stretch"
- align: Var[LiteralAlign]
+ align: Var[Responsive[LiteralAlign]]
# Alignment of children along the cross axis: "start" | "center" | "end" | "between"
- justify: Var[LiteralJustify]
+ justify: Var[Responsive[LiteralJustify]]
# Gap between children: "0" - "9"
- spacing: Var[LiteralSpacing]
+ spacing: Var[Responsive[LiteralSpacing]]
# Gap between children horizontal: "0" - "9"
- spacing_x: Var[LiteralSpacing]
+ spacing_x: Var[Responsive[LiteralSpacing]]
# Gap between children vertical: "0" - "9"
- spacing_y: Var[LiteralSpacing]
+ spacing_y: Var[Responsive[LiteralSpacing]]
# Reflex maps the "spacing" prop to "gap" prop.
_rename_props: Dict[str, str] = {
@@ -55,3 +56,6 @@ class Grid(el.Div, RadixThemesComponent):
"spacing_x": "gap_x",
"spacing_y": "gap_y",
}
+
+
+grid = Grid.create
diff --git a/reflex/components/radix/themes/layout/grid.pyi b/reflex/components/radix/themes/layout/grid.pyi
index cfb9c447e..faf63712e 100644
--- a/reflex/components/radix/themes/layout/grid.pyi
+++ b/reflex/components/radix/themes/layout/grid.pyi
@@ -1,156 +1,178 @@
"""Stub file for reflex/components/radix/themes/layout/grid.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.components.el import elements
+from reflex.event import EventType
from reflex.style import Style
-from typing import Dict, Literal
-from reflex import el
-from reflex.vars import Var
-from ..base import LiteralAlign, LiteralJustify, LiteralSpacing, RadixThemesComponent
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
LiteralGridFlow = Literal["row", "column", "dense", "row-dense", "column-dense"]
-class Grid(el.Div, RadixThemesComponent):
+class Grid(elements.Div, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
cls,
*children,
as_child: Optional[Union[Var[bool], bool]] = None,
- columns: Optional[Union[Var[str], str]] = None,
- rows: Optional[Union[Var[str], str]] = None,
+ columns: Optional[
+ Union[Breakpoints[str, str], Var[Union[Breakpoints[str, str], str]], str]
+ ] = None,
+ rows: Optional[
+ Union[Breakpoints[str, str], Var[Union[Breakpoints[str, str], str]], str]
+ ] = None,
flow: Optional[
Union[
- Var[Literal["row", "column", "dense", "row-dense", "column-dense"]],
- Literal["row", "column", "dense", "row-dense", "column-dense"],
+ Breakpoints[
+ str, Literal["column", "column-dense", "dense", "row", "row-dense"]
+ ],
+ Literal["column", "column-dense", "dense", "row", "row-dense"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Literal[
+ "column", "column-dense", "dense", "row", "row-dense"
+ ],
+ ],
+ Literal["column", "column-dense", "dense", "row", "row-dense"],
+ ]
+ ],
]
] = None,
align: Optional[
Union[
- Var[Literal["start", "center", "end", "baseline", "stretch"]],
- Literal["start", "center", "end", "baseline", "stretch"],
+ Breakpoints[
+ str, Literal["baseline", "center", "end", "start", "stretch"]
+ ],
+ Literal["baseline", "center", "end", "start", "stretch"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Literal["baseline", "center", "end", "start", "stretch"],
+ ],
+ Literal["baseline", "center", "end", "start", "stretch"],
+ ]
+ ],
]
] = None,
justify: Optional[
Union[
- Var[Literal["start", "center", "end", "between"]],
- Literal["start", "center", "end", "between"],
+ Breakpoints[str, Literal["between", "center", "end", "start"]],
+ Literal["between", "center", "end", "start"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["between", "center", "end", "start"]],
+ Literal["between", "center", "end", "start"],
+ ]
+ ],
]
] = None,
spacing: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[
+ str, Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
+ ],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ],
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ]
+ ],
]
] = None,
spacing_x: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[
+ str, Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
+ ],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ],
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ]
+ ],
]
] = None,
spacing_y: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[
+ str, Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
+ ],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ],
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ]
+ ],
]
] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Grid":
"""Create a new component instance.
@@ -196,3 +218,5 @@ class Grid(el.Div, RadixThemesComponent):
A new component instance.
"""
...
+
+grid = Grid.create
diff --git a/reflex/components/radix/themes/layout/list.py b/reflex/components/radix/themes/layout/list.py
index 87b9cf012..d83fd168b 100644
--- a/reflex/components/radix/themes/layout/list.py
+++ b/reflex/components/radix/themes/layout/list.py
@@ -1,15 +1,15 @@
"""List components."""
+
from __future__ import annotations
-from typing import Iterable, Literal, Optional, Union
+from typing import Any, Iterable, Literal, Union
from reflex.components.component import Component, ComponentNamespace
from reflex.components.core.foreach import Foreach
from reflex.components.el.elements.typography import Li, Ol, Ul
from reflex.components.lucide.icon import Icon
from reflex.components.radix.themes.typography.text import Text
-from reflex.style import Style
-from reflex.vars import Var
+from reflex.vars.base import Var
LiteralListStyleTypeUnordered = Literal[
"none",
@@ -44,33 +44,35 @@ class BaseList(Component):
# The style of the list. Default to "none".
list_style_type: Var[
Union[LiteralListStyleTypeUnordered, LiteralListStyleTypeOrdered]
- ]
+ ] = Var.create("none")
+
+ # A list of items to add to the list.
+ items: Var[Iterable] = Var.create([])
@classmethod
def create(
cls,
*children,
- items: Optional[Var[Iterable]] = None,
**props,
):
"""Create a list component.
Args:
*children: The children of the component.
- items: A list of items to add to the list.
**props: The properties of the component.
Returns:
The list component.
"""
+ items = props.pop("items", None)
list_style_type = props.pop("list_style_type", "none")
+
if not children and items is not None:
if isinstance(items, Var):
children = [Foreach.create(items, ListItem.create)]
else:
children = [ListItem.create(item) for item in items] # type: ignore
- props["list_style_position"] = "outside"
props["direction"] = "column"
style = props.setdefault("style", {})
style["list_style_type"] = list_style_type
@@ -78,18 +80,18 @@ class BaseList(Component):
style["gap"] = props["gap"]
return super().create(*children, **props)
- def add_style(self) -> Style | None:
+ def add_style(self) -> dict[str, Any] | None:
"""Add style to the component.
Returns:
The style of the component.
"""
- return Style(
- {
- "direction": "column",
- "list_style_position": "inside",
- }
- )
+ return {
+ "direction": "column",
+ }
+
+ def _exclude_props(self) -> list[str]:
+ return ["items", "list_style_type"]
class UnorderedList(BaseList, Ul):
@@ -101,22 +103,21 @@ class UnorderedList(BaseList, Ul):
def create(
cls,
*children,
- items: Optional[Var[Iterable]] = None,
- list_style_type: LiteralListStyleTypeUnordered = "disc",
**props,
):
- """Create a unordered list component.
+ """Create an unordered list component.
Args:
*children: The children of the component.
- items: A list of items to add to the list.
- list_style_type: The style of the list.
**props: The properties of the component.
Returns:
The list component.
"""
+ items = props.pop("items", None)
+ list_style_type = props.pop("list_style_type", "disc")
+
props["margin_left"] = props.get("margin_left", "1.5rem")
return super().create(
*children, items=items, list_style_type=list_style_type, **props
@@ -132,22 +133,21 @@ class OrderedList(BaseList, Ol):
def create(
cls,
*children,
- items: Optional[Var[Iterable]] = None,
- list_style_type: LiteralListStyleTypeOrdered = "decimal",
**props,
):
"""Create an ordered list component.
Args:
*children: The children of the component.
- items: A list of items to add to the list.
- list_style_type: The style of the list.
**props: The properties of the component.
Returns:
The list component.
"""
+ items = props.pop("items", None)
+ list_style_type = props.pop("list_style_type", "decimal")
+
props["margin_left"] = props.get("margin_left", "1.5rem")
return super().create(
*children, items=items, list_style_type=list_style_type, **props
@@ -187,3 +187,17 @@ class List(ComponentNamespace):
list_ns = List()
+list_item = list_ns.item
+ordered_list = list_ns.ordered
+unordered_list = list_ns.unordered
+
+
+def __getattr__(name):
+ # special case for when accessing list to avoid shadowing
+ # python's built in list object.
+ if name == "list":
+ return list_ns
+ try:
+ return globals()[name]
+ except KeyError:
+ raise AttributeError(f"module '{__name__} has no attribute '{name}'") from None
diff --git a/reflex/components/radix/themes/layout/list.pyi b/reflex/components/radix/themes/layout/list.pyi
index a736f106c..1ce6359a4 100644
--- a/reflex/components/radix/themes/layout/list.pyi
+++ b/reflex/components/radix/themes/layout/list.pyi
@@ -1,20 +1,15 @@
"""Stub file for reflex/components/radix/themes/layout/list.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Iterable, Literal, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Iterable, Literal, Optional, Union
from reflex.components.component import Component, ComponentNamespace
-from reflex.components.core.foreach import Foreach
from reflex.components.el.elements.typography import Li, Ol, Ul
-from reflex.components.lucide.icon import Icon
-from reflex.components.radix.themes.typography.text import Text
+from reflex.event import EventType
from reflex.style import Style
-from reflex.vars import Var
+from reflex.vars.base import Var
LiteralListStyleTypeUnordered = Literal["none", "disc", "circle", "square"]
LiteralListStyleTypeOrdered = Literal[
@@ -40,110 +35,78 @@ class BaseList(Component):
def create( # type: ignore
cls,
*children,
- items: Optional[Union[Var[Iterable], Iterable]] = None,
list_style_type: Optional[
Union[
+ Literal[
+ "armenian",
+ "decimal",
+ "decimal-leading-zero",
+ "georgian",
+ "hiragana",
+ "katakana",
+ "lower-alpha",
+ "lower-greek",
+ "lower-latin",
+ "lower-roman",
+ "none",
+ "upper-alpha",
+ "upper-latin",
+ "upper-roman",
+ ],
+ Literal["circle", "disc", "none", "square"],
Var[
Union[
- Literal["none", "disc", "circle", "square"],
Literal[
- "none",
+ "armenian",
"decimal",
"decimal-leading-zero",
- "lower-roman",
- "upper-roman",
- "lower-greek",
- "lower-latin",
- "upper-latin",
- "armenian",
"georgian",
- "lower-alpha",
- "upper-alpha",
"hiragana",
"katakana",
+ "lower-alpha",
+ "lower-greek",
+ "lower-latin",
+ "lower-roman",
+ "none",
+ "upper-alpha",
+ "upper-latin",
+ "upper-roman",
],
+ Literal["circle", "disc", "none", "square"],
]
],
- Union[
- Literal["none", "disc", "circle", "square"],
- Literal[
- "none",
- "decimal",
- "decimal-leading-zero",
- "lower-roman",
- "upper-roman",
- "lower-greek",
- "lower-latin",
- "upper-latin",
- "armenian",
- "georgian",
- "lower-alpha",
- "upper-alpha",
- "hiragana",
- "katakana",
- ],
- ],
]
] = None,
+ items: Optional[Union[Iterable, Var[Iterable]]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "BaseList":
"""Create a list component.
Args:
*children: The children of the component.
- items: A list of items to add to the list.
list_style_type: The style of the list. Default to "none".
+ items: A list of items to add to the list.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -157,7 +120,8 @@ class BaseList(Component):
"""
...
- def add_style(self) -> Style | None: ...
+
+ def add_style(self) -> dict[str, Any] | None: ...
class UnorderedList(BaseList, Ul):
@overload
@@ -165,107 +129,102 @@ class UnorderedList(BaseList, Ul):
def create( # type: ignore
cls,
*children,
- items: Optional[Union[Var[Iterable], Iterable]] = None,
- list_style_type: Optional[LiteralListStyleTypeUnordered] = "disc",
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ list_style_type: Optional[
+ Union[
+ Literal[
+ "armenian",
+ "decimal",
+ "decimal-leading-zero",
+ "georgian",
+ "hiragana",
+ "katakana",
+ "lower-alpha",
+ "lower-greek",
+ "lower-latin",
+ "lower-roman",
+ "none",
+ "upper-alpha",
+ "upper-latin",
+ "upper-roman",
+ ],
+ Literal["circle", "disc", "none", "square"],
+ Var[
+ Union[
+ Literal[
+ "armenian",
+ "decimal",
+ "decimal-leading-zero",
+ "georgian",
+ "hiragana",
+ "katakana",
+ "lower-alpha",
+ "lower-greek",
+ "lower-latin",
+ "lower-roman",
+ "none",
+ "upper-alpha",
+ "upper-latin",
+ "upper-roman",
+ ],
+ Literal["circle", "disc", "none", "square"],
+ ]
+ ],
+ ]
] = None,
+ items: Optional[Union[Iterable, Var[Iterable]]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "UnorderedList":
- """Create a unordered list component.
+ """Create an unordered list component.
Args:
*children: The children of the component.
+ list_style_type: The style of the list. Default to "none".
items: A list of items to add to the list.
- list_style_type: The style of the list.
access_key: Provides a hint for generating a keyboard shortcut for the current element.
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
content_editable: Indicates whether the element's content is editable.
@@ -302,114 +261,105 @@ class OrderedList(BaseList, Ol):
def create( # type: ignore
cls,
*children,
- items: Optional[Union[Var[Iterable], Iterable]] = None,
- list_style_type: Optional[LiteralListStyleTypeOrdered] = "decimal",
- reversed: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- start: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- type: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ list_style_type: Optional[
+ Union[
+ Literal[
+ "armenian",
+ "decimal",
+ "decimal-leading-zero",
+ "georgian",
+ "hiragana",
+ "katakana",
+ "lower-alpha",
+ "lower-greek",
+ "lower-latin",
+ "lower-roman",
+ "none",
+ "upper-alpha",
+ "upper-latin",
+ "upper-roman",
+ ],
+ Literal["circle", "disc", "none", "square"],
+ Var[
+ Union[
+ Literal[
+ "armenian",
+ "decimal",
+ "decimal-leading-zero",
+ "georgian",
+ "hiragana",
+ "katakana",
+ "lower-alpha",
+ "lower-greek",
+ "lower-latin",
+ "lower-roman",
+ "none",
+ "upper-alpha",
+ "upper-latin",
+ "upper-roman",
+ ],
+ Literal["circle", "disc", "none", "square"],
+ ]
+ ],
+ ]
] = None,
+ items: Optional[Union[Iterable, Var[Iterable]]] = None,
+ reversed: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ start: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ type: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "OrderedList":
"""Create an ordered list component.
Args:
*children: The children of the component.
+ list_style_type: The style of the list. Default to "none".
items: A list of items to add to the list.
- list_style_type: The style of the list.
reversed: Reverses the order of the list.
start: Specifies the start value of the first list item in an ordered list.
type: Specifies the kind of marker to use in the list (letters or numbers).
@@ -449,98 +399,52 @@ class ListItem(Li):
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ListItem":
"""Create a list item component.
@@ -584,110 +488,78 @@ class List(ComponentNamespace):
@staticmethod
def __call__(
*children,
- items: Optional[Union[Var[Iterable], Iterable]] = None,
list_style_type: Optional[
Union[
+ Literal[
+ "armenian",
+ "decimal",
+ "decimal-leading-zero",
+ "georgian",
+ "hiragana",
+ "katakana",
+ "lower-alpha",
+ "lower-greek",
+ "lower-latin",
+ "lower-roman",
+ "none",
+ "upper-alpha",
+ "upper-latin",
+ "upper-roman",
+ ],
+ Literal["circle", "disc", "none", "square"],
Var[
Union[
- Literal["none", "disc", "circle", "square"],
Literal[
- "none",
+ "armenian",
"decimal",
"decimal-leading-zero",
- "lower-roman",
- "upper-roman",
- "lower-greek",
- "lower-latin",
- "upper-latin",
- "armenian",
"georgian",
- "lower-alpha",
- "upper-alpha",
"hiragana",
"katakana",
+ "lower-alpha",
+ "lower-greek",
+ "lower-latin",
+ "lower-roman",
+ "none",
+ "upper-alpha",
+ "upper-latin",
+ "upper-roman",
],
+ Literal["circle", "disc", "none", "square"],
]
],
- Union[
- Literal["none", "disc", "circle", "square"],
- Literal[
- "none",
- "decimal",
- "decimal-leading-zero",
- "lower-roman",
- "upper-roman",
- "lower-greek",
- "lower-latin",
- "upper-latin",
- "armenian",
- "georgian",
- "lower-alpha",
- "upper-alpha",
- "hiragana",
- "katakana",
- ],
- ],
]
] = None,
+ items: Optional[Union[Iterable, Var[Iterable]]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "BaseList":
"""Create a list component.
Args:
*children: The children of the component.
- items: A list of items to add to the list.
list_style_type: The style of the list. Default to "none".
+ items: A list of items to add to the list.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -703,3 +575,6 @@ class List(ComponentNamespace):
...
list_ns = List()
+list_item = list_ns.item
+ordered_list = list_ns.ordered
+unordered_list = list_ns.unordered
diff --git a/reflex/components/radix/themes/layout/section.py b/reflex/components/radix/themes/layout/section.py
index 5f17b270c..68a131751 100644
--- a/reflex/components/radix/themes/layout/section.py
+++ b/reflex/components/radix/themes/layout/section.py
@@ -1,20 +1,25 @@
"""Declarative layout and common spacing props."""
+
from __future__ import annotations
from typing import Literal
-from reflex import el
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.components.el import elements
+from reflex.vars.base import LiteralVar, Var
from ..base import RadixThemesComponent
LiteralSectionSize = Literal["1", "2", "3"]
-class Section(el.Section, RadixThemesComponent):
+class Section(elements.Section, RadixThemesComponent):
"""Denotes a section of page content."""
tag = "Section"
- # The size of the section: "1" - "3" (default "3")
- size: Var[LiteralSectionSize]
+ # The size of the section: "1" - "3" (default "2")
+ size: Var[Responsive[LiteralSectionSize]] = LiteralVar.create("2")
+
+
+section = Section.create
diff --git a/reflex/components/radix/themes/layout/section.pyi b/reflex/components/radix/themes/layout/section.pyi
index 5b9ef9c5f..9fb790b9f 100644
--- a/reflex/components/radix/themes/layout/section.pyi
+++ b/reflex/components/radix/themes/layout/section.pyi
@@ -1,120 +1,83 @@
"""Stub file for reflex/components/radix/themes/layout/section.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.components.el import elements
+from reflex.event import EventType
from reflex.style import Style
-from typing import Literal
-from reflex import el
-from reflex.vars import Var
+from reflex.vars.base import Var
+
from ..base import RadixThemesComponent
LiteralSectionSize = Literal["1", "2", "3"]
-class Section(el.Section, RadixThemesComponent):
+class Section(elements.Section, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
cls,
*children,
size: Optional[
- Union[Var[Literal["1", "2", "3"]], Literal["1", "2", "3"]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]],
+ Literal["1", "2", "3"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["1", "2", "3"]], Literal["1", "2", "3"]
+ ]
+ ],
+ ]
] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Section":
"""Create a new component instance.
@@ -123,7 +86,7 @@ class Section(el.Section, RadixThemesComponent):
Args:
*children: Child components.
- size: The size of the section: "1" - "3" (default "3")
+ size: The size of the section: "1" - "3" (default "2")
access_key: Provides a hint for generating a keyboard shortcut for the current element.
auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user.
content_editable: Indicates whether the element's content is editable.
@@ -152,3 +115,5 @@ class Section(el.Section, RadixThemesComponent):
A new component instance.
"""
...
+
+section = Section.create
diff --git a/reflex/components/radix/themes/layout/spacer.py b/reflex/components/radix/themes/layout/spacer.py
index 6d7ab9aaf..9579b0b27 100644
--- a/reflex/components/radix/themes/layout/spacer.py
+++ b/reflex/components/radix/themes/layout/spacer.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from reflex.style import Style
+from typing import Any
from .flex import Flex
@@ -10,16 +10,17 @@ from .flex import Flex
class Spacer(Flex):
"""A spacer component."""
- def add_style(self) -> Style | None:
+ def add_style(self) -> dict[str, Any] | None:
"""Add style to the component.
Returns:
The style of the component.
"""
- return Style(
- {
- "flex": 1,
- "justify_self": "stretch",
- "align_self": "stretch",
- }
- )
+ return {
+ "flex": 1,
+ "justify_self": "stretch",
+ "align_self": "stretch",
+ }
+
+
+spacer = Spacer.create
diff --git a/reflex/components/radix/themes/layout/spacer.pyi b/reflex/components/radix/themes/layout/spacer.pyi
index 733501489..f83d7a4c9 100644
--- a/reflex/components/radix/themes/layout/spacer.pyi
+++ b/reflex/components/radix/themes/layout/spacer.pyi
@@ -1,17 +1,19 @@
"""Stub file for reflex/components/radix/themes/layout/spacer.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
+
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.event import EventType
from reflex.style import Style
+from reflex.vars.base import Var
+
from .flex import Flex
class Spacer(Flex):
- def add_style(self) -> Style | None: ...
+ def add_style(self) -> dict[str, Any] | None: ...
@overload
@classmethod
def create( # type: ignore
@@ -20,126 +22,125 @@ class Spacer(Flex):
as_child: Optional[Union[Var[bool], bool]] = None,
direction: Optional[
Union[
- Var[Literal["row", "column", "row-reverse", "column-reverse"]],
- Literal["row", "column", "row-reverse", "column-reverse"],
+ Breakpoints[
+ str, Literal["column", "column-reverse", "row", "row-reverse"]
+ ],
+ Literal["column", "column-reverse", "row", "row-reverse"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Literal["column", "column-reverse", "row", "row-reverse"],
+ ],
+ Literal["column", "column-reverse", "row", "row-reverse"],
+ ]
+ ],
]
] = None,
align: Optional[
Union[
- Var[Literal["start", "center", "end", "baseline", "stretch"]],
- Literal["start", "center", "end", "baseline", "stretch"],
+ Breakpoints[
+ str, Literal["baseline", "center", "end", "start", "stretch"]
+ ],
+ Literal["baseline", "center", "end", "start", "stretch"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Literal["baseline", "center", "end", "start", "stretch"],
+ ],
+ Literal["baseline", "center", "end", "start", "stretch"],
+ ]
+ ],
]
] = None,
justify: Optional[
Union[
- Var[Literal["start", "center", "end", "between"]],
- Literal["start", "center", "end", "between"],
+ Breakpoints[str, Literal["between", "center", "end", "start"]],
+ Literal["between", "center", "end", "start"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["between", "center", "end", "start"]],
+ Literal["between", "center", "end", "start"],
+ ]
+ ],
]
] = None,
wrap: Optional[
Union[
- Var[Literal["nowrap", "wrap", "wrap-reverse"]],
+ Breakpoints[str, Literal["nowrap", "wrap", "wrap-reverse"]],
Literal["nowrap", "wrap", "wrap-reverse"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["nowrap", "wrap", "wrap-reverse"]],
+ Literal["nowrap", "wrap", "wrap-reverse"],
+ ]
+ ],
]
] = None,
spacing: Optional[
Union[
- Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[
+ str, Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
+ ],
Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ],
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ]
+ ],
]
] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Spacer":
"""Create a new component instance.
@@ -182,3 +183,5 @@ class Spacer(Flex):
A new component instance.
"""
...
+
+spacer = Spacer.create
diff --git a/reflex/components/radix/themes/layout/stack.py b/reflex/components/radix/themes/layout/stack.py
index 8f0abf433..d11c3488b 100644
--- a/reflex/components/radix/themes/layout/stack.py
+++ b/reflex/components/radix/themes/layout/stack.py
@@ -3,7 +3,7 @@
from __future__ import annotations
from reflex.components.component import Component
-from reflex.vars import Var
+from reflex.vars.base import Var
from ..base import LiteralAlign, LiteralSpacing
from .flex import Flex, LiteralFlexDirection
@@ -12,20 +12,22 @@ from .flex import Flex, LiteralFlexDirection
class Stack(Flex):
"""A stack component."""
+ # The spacing between each stack item.
+ spacing: Var[LiteralSpacing] = Var.create("3")
+
+ # The alignment of the stack items.
+ align: Var[LiteralAlign] = Var.create("start")
+
@classmethod
def create(
cls,
*children,
- spacing: LiteralSpacing = "3",
- align: LiteralAlign = "start",
**props,
) -> Component:
"""Create a new instance of the component.
Args:
*children: The children of the stack.
- spacing: The spacing between each stack item.
- align: The alignment of the stack items.
**props: The properties of the stack.
Returns:
@@ -33,14 +35,12 @@ class Stack(Flex):
"""
# Apply the default classname
given_class_name = props.pop("class_name", [])
- if isinstance(given_class_name, str):
+ if not isinstance(given_class_name, list):
given_class_name = [given_class_name]
props["class_name"] = ["rx-Stack", *given_class_name]
return super().create(
*children,
- spacing=spacing,
- align=align,
**props,
)
@@ -57,3 +57,8 @@ class HStack(Stack):
# The direction of the stack.
direction: Var[LiteralFlexDirection] = "row" # type: ignore
+
+
+stack = Stack.create
+hstack = HStack.create
+vstack = VStack.create
diff --git a/reflex/components/radix/themes/layout/stack.pyi b/reflex/components/radix/themes/layout/stack.pyi
index c35f1dad8..c4b475218 100644
--- a/reflex/components/radix/themes/layout/stack.pyi
+++ b/reflex/components/radix/themes/layout/stack.pyi
@@ -1,16 +1,16 @@
"""Stub file for reflex/components/radix/themes/layout/stack.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.event import EventType
from reflex.style import Style
-from reflex.components.component import Component
-from reflex.vars import Var
-from ..base import LiteralAlign, LiteralSpacing
-from .flex import Flex, LiteralFlexDirection
+from reflex.vars.base import Var
+
+from .flex import Flex
class Stack(Flex):
@overload
@@ -18,126 +18,113 @@ class Stack(Flex):
def create( # type: ignore
cls,
*children,
- spacing: Optional[LiteralSpacing] = "3",
- align: Optional[LiteralAlign] = "start",
+ spacing: Optional[
+ Union[
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ ]
+ ] = None,
+ align: Optional[
+ Union[
+ Literal["baseline", "center", "end", "start", "stretch"],
+ Var[Literal["baseline", "center", "end", "start", "stretch"]],
+ ]
+ ] = None,
as_child: Optional[Union[Var[bool], bool]] = None,
direction: Optional[
Union[
- Var[Literal["row", "column", "row-reverse", "column-reverse"]],
- Literal["row", "column", "row-reverse", "column-reverse"],
+ Breakpoints[
+ str, Literal["column", "column-reverse", "row", "row-reverse"]
+ ],
+ Literal["column", "column-reverse", "row", "row-reverse"],
+ Var[
+ Union[
+ Breakpoints[
+ str,
+ Literal["column", "column-reverse", "row", "row-reverse"],
+ ],
+ Literal["column", "column-reverse", "row", "row-reverse"],
+ ]
+ ],
]
] = None,
justify: Optional[
Union[
- Var[Literal["start", "center", "end", "between"]],
- Literal["start", "center", "end", "between"],
+ Breakpoints[str, Literal["between", "center", "end", "start"]],
+ Literal["between", "center", "end", "start"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["between", "center", "end", "start"]],
+ Literal["between", "center", "end", "start"],
+ ]
+ ],
]
] = None,
wrap: Optional[
Union[
- Var[Literal["nowrap", "wrap", "wrap-reverse"]],
+ Breakpoints[str, Literal["nowrap", "wrap", "wrap-reverse"]],
Literal["nowrap", "wrap", "wrap-reverse"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["nowrap", "wrap", "wrap-reverse"]],
+ Literal["nowrap", "wrap", "wrap-reverse"],
+ ]
+ ],
]
] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Stack":
"""Create a new instance of the component.
Args:
*children: The children of the stack.
- spacing: The spacing between each stack item.
- align: The alignment of the stack items.
+ spacing: Gap between children: "0" - "9"
+ align: Alignment of children along the main axis: "start" | "center" | "end" | "baseline" | "stretch"
as_child: Change the default rendered element for the one passed as a child, merging their props and behavior.
direction: How child items are layed out: "row" | "column" | "row-reverse" | "column-reverse"
justify: Alignment of children along the cross axis: "start" | "center" | "end" | "between"
@@ -177,127 +164,103 @@ class VStack(Stack):
def create( # type: ignore
cls,
*children,
- spacing: Optional[LiteralSpacing] = "3",
- align: Optional[LiteralAlign] = "start",
direction: Optional[
Union[
- Var[Literal["row", "column", "row-reverse", "column-reverse"]],
- Literal["row", "column", "row-reverse", "column-reverse"],
+ Literal["column", "column-reverse", "row", "row-reverse"],
+ Var[Literal["column", "column-reverse", "row", "row-reverse"]],
+ ]
+ ] = None,
+ spacing: Optional[
+ Union[
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ ]
+ ] = None,
+ align: Optional[
+ Union[
+ Literal["baseline", "center", "end", "start", "stretch"],
+ Var[Literal["baseline", "center", "end", "start", "stretch"]],
]
] = None,
as_child: Optional[Union[Var[bool], bool]] = None,
justify: Optional[
Union[
- Var[Literal["start", "center", "end", "between"]],
- Literal["start", "center", "end", "between"],
+ Breakpoints[str, Literal["between", "center", "end", "start"]],
+ Literal["between", "center", "end", "start"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["between", "center", "end", "start"]],
+ Literal["between", "center", "end", "start"],
+ ]
+ ],
]
] = None,
wrap: Optional[
Union[
- Var[Literal["nowrap", "wrap", "wrap-reverse"]],
+ Breakpoints[str, Literal["nowrap", "wrap", "wrap-reverse"]],
Literal["nowrap", "wrap", "wrap-reverse"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["nowrap", "wrap", "wrap-reverse"]],
+ Literal["nowrap", "wrap", "wrap-reverse"],
+ ]
+ ],
]
] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "VStack":
"""Create a new instance of the component.
Args:
*children: The children of the stack.
- spacing: The spacing between each stack item.
- align: The alignment of the stack items.
direction: How child items are layed out: "row" | "column" | "row-reverse" | "column-reverse"
+ spacing: Gap between children: "0" - "9"
+ align: Alignment of children along the main axis: "start" | "center" | "end" | "baseline" | "stretch"
as_child: Change the default rendered element for the one passed as a child, merging their props and behavior.
justify: Alignment of children along the cross axis: "start" | "center" | "end" | "between"
wrap: Whether children should wrap when they reach the end of their container: "nowrap" | "wrap" | "wrap-reverse"
@@ -336,127 +299,103 @@ class HStack(Stack):
def create( # type: ignore
cls,
*children,
- spacing: Optional[LiteralSpacing] = "3",
- align: Optional[LiteralAlign] = "start",
direction: Optional[
Union[
- Var[Literal["row", "column", "row-reverse", "column-reverse"]],
- Literal["row", "column", "row-reverse", "column-reverse"],
+ Literal["column", "column-reverse", "row", "row-reverse"],
+ Var[Literal["column", "column-reverse", "row", "row-reverse"]],
+ ]
+ ] = None,
+ spacing: Optional[
+ Union[
+ Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ ]
+ ] = None,
+ align: Optional[
+ Union[
+ Literal["baseline", "center", "end", "start", "stretch"],
+ Var[Literal["baseline", "center", "end", "start", "stretch"]],
]
] = None,
as_child: Optional[Union[Var[bool], bool]] = None,
justify: Optional[
Union[
- Var[Literal["start", "center", "end", "between"]],
- Literal["start", "center", "end", "between"],
+ Breakpoints[str, Literal["between", "center", "end", "start"]],
+ Literal["between", "center", "end", "start"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["between", "center", "end", "start"]],
+ Literal["between", "center", "end", "start"],
+ ]
+ ],
]
] = None,
wrap: Optional[
Union[
- Var[Literal["nowrap", "wrap", "wrap-reverse"]],
+ Breakpoints[str, Literal["nowrap", "wrap", "wrap-reverse"]],
Literal["nowrap", "wrap", "wrap-reverse"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["nowrap", "wrap", "wrap-reverse"]],
+ Literal["nowrap", "wrap", "wrap-reverse"],
+ ]
+ ],
]
] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "HStack":
"""Create a new instance of the component.
Args:
*children: The children of the stack.
- spacing: The spacing between each stack item.
- align: The alignment of the stack items.
direction: How child items are layed out: "row" | "column" | "row-reverse" | "column-reverse"
+ spacing: Gap between children: "0" - "9"
+ align: Alignment of children along the main axis: "start" | "center" | "end" | "baseline" | "stretch"
as_child: Change the default rendered element for the one passed as a child, merging their props and behavior.
justify: Alignment of children along the cross axis: "start" | "center" | "end" | "between"
wrap: Whether children should wrap when they reach the end of their container: "nowrap" | "wrap" | "wrap-reverse"
@@ -488,3 +427,7 @@ class HStack(Stack):
The stack component.
"""
...
+
+stack = Stack.create
+hstack = HStack.create
+vstack = VStack.create
diff --git a/reflex/components/radix/themes/typography/__init__.py b/reflex/components/radix/themes/typography/__init__.py
index a14e21007..0ea695ac5 100644
--- a/reflex/components/radix/themes/typography/__init__.py
+++ b/reflex/components/radix/themes/typography/__init__.py
@@ -1,20 +1,16 @@
"""Typographic components."""
-from .blockquote import Blockquote
-from .code import Code
-from .heading import Heading
-from .link import Link
-from .text import text
+from __future__ import annotations
-blockquote = Blockquote.create
-code = Code.create
-heading = Heading.create
-link = Link.create
+from reflex import RADIX_THEMES_TYPOGRAPHY_MAPPING
+from reflex.utils import lazy_loader
-__all__ = [
- "blockquote",
- "code",
- "heading",
- "link",
- "text",
-]
+_SUBMOD_ATTRS: dict[str, list[str]] = {
+ "".join(k.split("components.radix.themes.typography.")[-1]): v
+ for k, v in RADIX_THEMES_TYPOGRAPHY_MAPPING.items()
+}
+
+__getattr__, __dir__, __all__ = lazy_loader.attach(
+ __name__,
+ submod_attrs=_SUBMOD_ATTRS,
+)
diff --git a/reflex/components/radix/themes/typography/__init__.pyi b/reflex/components/radix/themes/typography/__init__.pyi
new file mode 100644
index 000000000..4cc8f01f2
--- /dev/null
+++ b/reflex/components/radix/themes/typography/__init__.pyi
@@ -0,0 +1,10 @@
+"""Stub file for reflex/components/radix/themes/typography/__init__.py"""
+# ------------------- DO NOT EDIT ----------------------
+# This file was generated by `reflex/utils/pyi_generator.py`!
+# ------------------------------------------------------
+
+from .blockquote import blockquote as blockquote
+from .code import code as code
+from .heading import heading as heading
+from .link import link as link
+from .text import text as text
diff --git a/reflex/components/radix/themes/typography/base.py b/reflex/components/radix/themes/typography/base.py
index 8742753b4..354d1b911 100644
--- a/reflex/components/radix/themes/typography/base.py
+++ b/reflex/components/radix/themes/typography/base.py
@@ -2,6 +2,7 @@
https://www.radix-ui.com/themes/docs/theme/typography
"""
+
from __future__ import annotations
from typing import Literal
diff --git a/reflex/components/radix/themes/typography/blockquote.py b/reflex/components/radix/themes/typography/blockquote.py
index 6525064d5..a60c05471 100644
--- a/reflex/components/radix/themes/typography/blockquote.py
+++ b/reflex/components/radix/themes/typography/blockquote.py
@@ -2,10 +2,12 @@
https://www.radix-ui.com/themes/docs/theme/typography
"""
+
from __future__ import annotations
-from reflex import el
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.components.el import elements
+from reflex.vars.base import Var
from ..base import (
LiteralAccentColor,
@@ -17,19 +19,22 @@ from .base import (
)
-class Blockquote(el.Blockquote, RadixThemesComponent):
+class Blockquote(elements.Blockquote, RadixThemesComponent):
"""A block level extended quotation."""
tag = "Blockquote"
# Text size: "1" - "9"
- size: Var[LiteralTextSize]
+ size: Var[Responsive[LiteralTextSize]]
# Thickness of text: "light" | "regular" | "medium" | "bold"
- weight: Var[LiteralTextWeight]
+ weight: Var[Responsive[LiteralTextWeight]]
# Overrides the accent color inherited from the Theme.
color_scheme: Var[LiteralAccentColor]
# Whether to render the text with higher contrast color
high_contrast: Var[bool]
+
+
+blockquote = Blockquote.create
diff --git a/reflex/components/radix/themes/typography/blockquote.pyi b/reflex/components/radix/themes/typography/blockquote.pyi
index 76855b287..3a9ae5c72 100644
--- a/reflex/components/radix/themes/typography/blockquote.pyi
+++ b/reflex/components/radix/themes/typography/blockquote.pyi
@@ -1,18 +1,19 @@
"""Stub file for reflex/components/radix/themes/typography/blockquote.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from reflex import el
-from reflex.vars import Var
-from ..base import LiteralAccentColor, RadixThemesComponent
-from .base import LiteralTextSize, LiteralTextWeight
-class Blockquote(el.Blockquote, RadixThemesComponent):
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.components.el import elements
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
+
+class Blockquote(elements.Blockquote, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
@@ -20,172 +21,140 @@ class Blockquote(el.Blockquote, RadixThemesComponent):
*children,
size: Optional[
Union[
- Var[Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]
+ ],
+ Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ]
+ ],
]
] = None,
weight: Optional[
Union[
- Var[Literal["light", "regular", "medium", "bold"]],
- Literal["light", "regular", "medium", "bold"],
+ Breakpoints[str, Literal["bold", "light", "medium", "regular"]],
+ Literal["bold", "light", "medium", "regular"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["bold", "light", "medium", "regular"]],
+ Literal["bold", "light", "medium", "regular"],
+ ]
+ ],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
- cite: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ cite: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Blockquote":
"""Create a new component instance.
@@ -227,3 +196,5 @@ class Blockquote(el.Blockquote, RadixThemesComponent):
A new component instance.
"""
...
+
+blockquote = Blockquote.create
diff --git a/reflex/components/radix/themes/typography/code.py b/reflex/components/radix/themes/typography/code.py
index 8ee0d2be2..663f260da 100644
--- a/reflex/components/radix/themes/typography/code.py
+++ b/reflex/components/radix/themes/typography/code.py
@@ -2,10 +2,12 @@
https://www.radix-ui.com/themes/docs/theme/typography
"""
+
from __future__ import annotations
-from reflex import el
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.components.el import elements
+from reflex.vars.base import Var
from ..base import (
LiteralAccentColor,
@@ -18,7 +20,7 @@ from .base import (
)
-class Code(el.Code, RadixThemesComponent):
+class Code(elements.Code, RadixThemesComponent):
"""A block level extended quotation."""
tag = "Code"
@@ -27,13 +29,16 @@ class Code(el.Code, RadixThemesComponent):
variant: Var[LiteralVariant]
# Text size: "1" - "9"
- size: Var[LiteralTextSize]
+ size: Var[Responsive[LiteralTextSize]]
# Thickness of text: "light" | "regular" | "medium" | "bold"
- weight: Var[LiteralTextWeight]
+ weight: Var[Responsive[LiteralTextWeight]]
# Overrides the accent color inherited from the Theme.
color_scheme: Var[LiteralAccentColor]
# Whether to render the text with higher contrast color
high_contrast: Var[bool]
+
+
+code = Code.create
diff --git a/reflex/components/radix/themes/typography/code.pyi b/reflex/components/radix/themes/typography/code.pyi
index 354c31cd1..2cda39ddf 100644
--- a/reflex/components/radix/themes/typography/code.pyi
+++ b/reflex/components/radix/themes/typography/code.pyi
@@ -1,18 +1,19 @@
"""Stub file for reflex/components/radix/themes/typography/code.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from reflex import el
-from reflex.vars import Var
-from ..base import LiteralAccentColor, LiteralVariant, RadixThemesComponent
-from .base import LiteralTextSize, LiteralTextWeight
-class Code(el.Code, RadixThemesComponent):
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.components.el import elements
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
+
+class Code(elements.Code, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
@@ -20,177 +21,145 @@ class Code(el.Code, RadixThemesComponent):
*children,
variant: Optional[
Union[
- Var[Literal["classic", "solid", "soft", "surface", "outline", "ghost"]],
- Literal["classic", "solid", "soft", "surface", "outline", "ghost"],
+ Literal["classic", "ghost", "outline", "soft", "solid", "surface"],
+ Var[Literal["classic", "ghost", "outline", "soft", "solid", "surface"]],
]
] = None,
size: Optional[
Union[
- Var[Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]
+ ],
+ Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ]
+ ],
]
] = None,
weight: Optional[
Union[
- Var[Literal["light", "regular", "medium", "bold"]],
- Literal["light", "regular", "medium", "bold"],
+ Breakpoints[str, Literal["bold", "light", "medium", "regular"]],
+ Literal["bold", "light", "medium", "regular"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["bold", "light", "medium", "regular"]],
+ Literal["bold", "light", "medium", "regular"],
+ ]
+ ],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Code":
"""Create a new component instance.
@@ -232,3 +201,5 @@ class Code(el.Code, RadixThemesComponent):
A new component instance.
"""
...
+
+code = Code.create
diff --git a/reflex/components/radix/themes/typography/heading.py b/reflex/components/radix/themes/typography/heading.py
index 729d06624..f5fec8bb1 100644
--- a/reflex/components/radix/themes/typography/heading.py
+++ b/reflex/components/radix/themes/typography/heading.py
@@ -2,10 +2,12 @@
https://www.radix-ui.com/themes/docs/theme/typography
"""
+
from __future__ import annotations
-from reflex import el
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.components.el import elements
+from reflex.vars.base import Var
from ..base import (
LiteralAccentColor,
@@ -19,7 +21,7 @@ from .base import (
)
-class Heading(el.H1, RadixThemesComponent):
+class Heading(elements.H1, RadixThemesComponent):
"""A foundational text primitive based on the element."""
tag = "Heading"
@@ -31,19 +33,22 @@ class Heading(el.H1, RadixThemesComponent):
as_: Var[str]
# Text size: "1" - "9"
- size: Var[LiteralTextSize]
+ size: Var[Responsive[LiteralTextSize]]
# Thickness of text: "light" | "regular" | "medium" | "bold"
- weight: Var[LiteralTextWeight]
+ weight: Var[Responsive[LiteralTextWeight]]
# Alignment of text in element: "left" | "center" | "right"
- align: Var[LiteralTextAlign]
+ align: Var[Responsive[LiteralTextAlign]]
# Removes the leading trim space: "normal" | "start" | "end" | "both"
- trim: Var[LiteralTextTrim]
+ trim: Var[Responsive[LiteralTextTrim]]
# Overrides the accent color inherited from the Theme.
color_scheme: Var[LiteralAccentColor]
# Whether to render the text with higher contrast color
high_contrast: Var[bool]
+
+
+heading = Heading.create
diff --git a/reflex/components/radix/themes/typography/heading.pyi b/reflex/components/radix/themes/typography/heading.pyi
index b10ea01ca..78ef8ba60 100644
--- a/reflex/components/radix/themes/typography/heading.pyi
+++ b/reflex/components/radix/themes/typography/heading.pyi
@@ -1,18 +1,19 @@
"""Stub file for reflex/components/radix/themes/typography/heading.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from reflex import el
-from reflex.vars import Var
-from ..base import LiteralAccentColor, RadixThemesComponent
-from .base import LiteralTextAlign, LiteralTextSize, LiteralTextTrim, LiteralTextWeight
-class Heading(el.H1, RadixThemesComponent):
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.components.el import elements
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
+
+class Heading(elements.H1, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
@@ -22,183 +23,163 @@ class Heading(el.H1, RadixThemesComponent):
as_: Optional[Union[Var[str], str]] = None,
size: Optional[
Union[
- Var[Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]
+ ],
+ Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ]
+ ],
]
] = None,
weight: Optional[
Union[
- Var[Literal["light", "regular", "medium", "bold"]],
- Literal["light", "regular", "medium", "bold"],
+ Breakpoints[str, Literal["bold", "light", "medium", "regular"]],
+ Literal["bold", "light", "medium", "regular"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["bold", "light", "medium", "regular"]],
+ Literal["bold", "light", "medium", "regular"],
+ ]
+ ],
]
] = None,
align: Optional[
Union[
- Var[Literal["left", "center", "right"]],
- Literal["left", "center", "right"],
+ Breakpoints[str, Literal["center", "left", "right"]],
+ Literal["center", "left", "right"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["center", "left", "right"]],
+ Literal["center", "left", "right"],
+ ]
+ ],
]
] = None,
trim: Optional[
Union[
- Var[Literal["normal", "start", "end", "both"]],
- Literal["normal", "start", "end", "both"],
+ Breakpoints[str, Literal["both", "end", "normal", "start"]],
+ Literal["both", "end", "normal", "start"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["both", "end", "normal", "start"]],
+ Literal["both", "end", "normal", "start"],
+ ]
+ ],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Heading":
"""Create a new component instance.
@@ -243,3 +224,5 @@ class Heading(el.H1, RadixThemesComponent):
A new component instance.
"""
...
+
+heading = Heading.create
diff --git a/reflex/components/radix/themes/typography/link.py b/reflex/components/radix/themes/typography/link.py
index 7a4e424ed..e51209dce 100644
--- a/reflex/components/radix/themes/typography/link.py
+++ b/reflex/components/radix/themes/typography/link.py
@@ -8,12 +8,13 @@ from __future__ import annotations
from typing import Literal
from reflex.components.component import Component, MemoizationLeaf
+from reflex.components.core.breakpoints import Responsive
from reflex.components.core.colors import color
from reflex.components.core.cond import cond
from reflex.components.el.elements.inline import A
from reflex.components.next.link import NextLink
-from reflex.utils import imports
-from reflex.vars import Var
+from reflex.utils.imports import ImportDict
+from reflex.vars.base import Var
from ..base import (
LiteralAccentColor,
@@ -39,13 +40,13 @@ class Link(RadixThemesComponent, A, MemoizationLeaf):
as_child: Var[bool]
# Text size: "1" - "9"
- size: Var[LiteralTextSize]
+ size: Var[Responsive[LiteralTextSize]]
# Thickness of text: "light" | "regular" | "medium" | "bold"
- weight: Var[LiteralTextWeight]
+ weight: Var[Responsive[LiteralTextWeight]]
# Removes the leading trim space: "normal" | "start" | "end" | "both"
- trim: Var[LiteralTextTrim]
+ trim: Var[Responsive[LiteralTextTrim]]
# Sets the visibility of the underline affordance: "auto" | "hover" | "always" | "none"
underline: Var[LiteralLinkUnderline]
@@ -59,8 +60,13 @@ class Link(RadixThemesComponent, A, MemoizationLeaf):
# If True, the link will open in a new tab
is_external: Var[bool]
- def _get_imports(self) -> imports.ImportDict:
- return {**super()._get_imports(), **next_link._get_imports()}
+ def add_imports(self) -> ImportDict:
+ """Add imports for the Link component.
+
+ Returns:
+ The import dict.
+ """
+ return next_link._get_imports() # type: ignore
@classmethod
def create(cls, *children, **props) -> Component:
@@ -102,3 +108,6 @@ class Link(RadixThemesComponent, A, MemoizationLeaf):
**props,
)
return super().create(*children, **props)
+
+
+link = Link.create
diff --git a/reflex/components/radix/themes/typography/link.pyi b/reflex/components/radix/themes/typography/link.pyi
index ebcb8dce6..3e3eaf64b 100644
--- a/reflex/components/radix/themes/typography/link.pyi
+++ b/reflex/components/radix/themes/typography/link.pyi
@@ -1,27 +1,26 @@
"""Stub file for reflex/components/radix/themes/typography/link.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Literal
-from reflex.components.component import Component, MemoizationLeaf
-from reflex.components.core.colors import color
-from reflex.components.core.cond import cond
+
+from reflex.components.component import MemoizationLeaf
+from reflex.components.core.breakpoints import Breakpoints
from reflex.components.el.elements.inline import A
from reflex.components.next.link import NextLink
-from reflex.utils import imports
-from reflex.vars import Var
-from ..base import LiteralAccentColor, RadixThemesComponent
-from .base import LiteralTextSize, LiteralTextTrim, LiteralTextWeight
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.utils.imports import ImportDict
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
LiteralLinkUnderline = Literal["auto", "hover", "always", "none"]
next_link = NextLink.create()
class Link(RadixThemesComponent, A, MemoizationLeaf):
+ def add_imports(self) -> ImportDict: ...
@overload
@classmethod
def create( # type: ignore
@@ -30,205 +29,169 @@ class Link(RadixThemesComponent, A, MemoizationLeaf):
as_child: Optional[Union[Var[bool], bool]] = None,
size: Optional[
Union[
- Var[Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]
+ ],
+ Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ]
+ ],
]
] = None,
weight: Optional[
Union[
- Var[Literal["light", "regular", "medium", "bold"]],
- Literal["light", "regular", "medium", "bold"],
+ Breakpoints[str, Literal["bold", "light", "medium", "regular"]],
+ Literal["bold", "light", "medium", "regular"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["bold", "light", "medium", "regular"]],
+ Literal["bold", "light", "medium", "regular"],
+ ]
+ ],
]
] = None,
trim: Optional[
Union[
- Var[Literal["normal", "start", "end", "both"]],
- Literal["normal", "start", "end", "both"],
+ Breakpoints[str, Literal["both", "end", "normal", "start"]],
+ Literal["both", "end", "normal", "start"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["both", "end", "normal", "start"]],
+ Literal["both", "end", "normal", "start"],
+ ]
+ ],
]
] = None,
underline: Optional[
Union[
- Var[Literal["auto", "hover", "always", "none"]],
- Literal["auto", "hover", "always", "none"],
+ Literal["always", "auto", "hover", "none"],
+ Var[Literal["always", "auto", "hover", "none"]],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
is_external: Optional[Union[Var[bool], bool]] = None,
- download: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- href: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- href_lang: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- media: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- ping: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
+ download: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ href: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ href_lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ media: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ ping: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
referrer_policy: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- rel: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- shape: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- target: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ rel: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ shape: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ target: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Link":
"""Create a Link component.
@@ -282,3 +245,5 @@ class Link(RadixThemesComponent, A, MemoizationLeaf):
Component: The link component
"""
...
+
+link = Link.create
diff --git a/reflex/components/radix/themes/typography/text.py b/reflex/components/radix/themes/typography/text.py
index 96512fe58..24b09c753 100644
--- a/reflex/components/radix/themes/typography/text.py
+++ b/reflex/components/radix/themes/typography/text.py
@@ -7,9 +7,10 @@ from __future__ import annotations
from typing import Literal
-from reflex import el
from reflex.components.component import ComponentNamespace
-from reflex.vars import Var
+from reflex.components.core.breakpoints import Responsive
+from reflex.components.el import elements
+from reflex.vars.base import Var
from ..base import (
LiteralAccentColor,
@@ -44,7 +45,7 @@ LiteralType = Literal[
]
-class Text(el.Span, RadixThemesComponent):
+class Text(elements.Span, RadixThemesComponent):
"""A foundational text primitive based on the element."""
tag = "Text"
@@ -56,16 +57,16 @@ class Text(el.Span, RadixThemesComponent):
as_: Var[LiteralType] = "p" # type: ignore
# Text size: "1" - "9"
- size: Var[LiteralTextSize]
+ size: Var[Responsive[LiteralTextSize]]
# Thickness of text: "light" | "regular" | "medium" | "bold"
- weight: Var[LiteralTextWeight]
+ weight: Var[Responsive[LiteralTextWeight]]
# Alignment of text in element: "left" | "center" | "right"
- align: Var[LiteralTextAlign]
+ align: Var[Responsive[LiteralTextAlign]]
# Removes the leading trim space: "normal" | "start" | "end" | "both"
- trim: Var[LiteralTextTrim]
+ trim: Var[Responsive[LiteralTextTrim]]
# Overrides the accent color inherited from the Theme.
color_scheme: Var[LiteralAccentColor]
@@ -80,13 +81,13 @@ class Span(Text):
as_: Var[LiteralType] = "span" # type: ignore
-class Em(el.Em, RadixThemesComponent):
+class Em(elements.Em, RadixThemesComponent):
"""Marks text to stress emphasis."""
tag = "Em"
-class Kbd(el.Kbd, RadixThemesComponent):
+class Kbd(elements.Kbd, RadixThemesComponent):
"""Represents keyboard input or a hotkey."""
tag = "Kbd"
@@ -95,13 +96,13 @@ class Kbd(el.Kbd, RadixThemesComponent):
size: Var[LiteralTextSize]
-class Quote(el.Q, RadixThemesComponent):
+class Quote(elements.Q, RadixThemesComponent):
"""A short inline quotation."""
tag = "Quote"
-class Strong(el.Strong, RadixThemesComponent):
+class Strong(elements.Strong, RadixThemesComponent):
"""Marks text to signify strong importance."""
tag = "Strong"
diff --git a/reflex/components/radix/themes/typography/text.pyi b/reflex/components/radix/themes/typography/text.pyi
index ea52eaca1..b4ddc622c 100644
--- a/reflex/components/radix/themes/typography/text.pyi
+++ b/reflex/components/radix/themes/typography/text.pyi
@@ -1,18 +1,18 @@
"""Stub file for reflex/components/radix/themes/typography/text.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Literal
-from reflex import el
+
from reflex.components.component import ComponentNamespace
-from reflex.vars import Var
-from ..base import LiteralAccentColor, RadixThemesComponent
-from .base import LiteralTextAlign, LiteralTextSize, LiteralTextTrim, LiteralTextWeight
+from reflex.components.core.breakpoints import Breakpoints
+from reflex.components.el import elements
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
+
+from ..base import RadixThemesComponent
LiteralType = Literal[
"p",
@@ -35,7 +35,7 @@ LiteralType = Literal[
"sup",
]
-class Text(el.Span, RadixThemesComponent):
+class Text(elements.Span, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
@@ -44,229 +44,209 @@ class Text(el.Span, RadixThemesComponent):
as_child: Optional[Union[Var[bool], bool]] = None,
as_: Optional[
Union[
- Var[
- Literal[
- "p",
- "label",
- "div",
- "span",
- "b",
- "i",
- "u",
- "abbr",
- "cite",
- "del",
- "em",
- "ins",
- "kbd",
- "mark",
- "s",
- "samp",
- "sub",
- "sup",
- ]
- ],
Literal[
- "p",
- "label",
- "div",
- "span",
- "b",
- "i",
- "u",
"abbr",
+ "b",
"cite",
"del",
+ "div",
"em",
+ "i",
"ins",
"kbd",
+ "label",
"mark",
+ "p",
"s",
"samp",
+ "span",
"sub",
"sup",
+ "u",
+ ],
+ Var[
+ Literal[
+ "abbr",
+ "b",
+ "cite",
+ "del",
+ "div",
+ "em",
+ "i",
+ "ins",
+ "kbd",
+ "label",
+ "mark",
+ "p",
+ "s",
+ "samp",
+ "span",
+ "sub",
+ "sup",
+ "u",
+ ]
],
]
] = None,
size: Optional[
Union[
- Var[Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]
+ ],
+ Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ]
+ ],
]
] = None,
weight: Optional[
Union[
- Var[Literal["light", "regular", "medium", "bold"]],
- Literal["light", "regular", "medium", "bold"],
+ Breakpoints[str, Literal["bold", "light", "medium", "regular"]],
+ Literal["bold", "light", "medium", "regular"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["bold", "light", "medium", "regular"]],
+ Literal["bold", "light", "medium", "regular"],
+ ]
+ ],
]
] = None,
align: Optional[
Union[
- Var[Literal["left", "center", "right"]],
- Literal["left", "center", "right"],
+ Breakpoints[str, Literal["center", "left", "right"]],
+ Literal["center", "left", "right"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["center", "left", "right"]],
+ Literal["center", "left", "right"],
+ ]
+ ],
]
] = None,
trim: Optional[
Union[
- Var[Literal["normal", "start", "end", "both"]],
- Literal["normal", "start", "end", "both"],
+ Breakpoints[str, Literal["both", "end", "normal", "start"]],
+ Literal["both", "end", "normal", "start"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["both", "end", "normal", "start"]],
+ Literal["both", "end", "normal", "start"],
+ ]
+ ],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Text":
"""Create a new component instance.
@@ -320,230 +300,210 @@ class Span(Text):
*children,
as_: Optional[
Union[
- Var[
- Literal[
- "p",
- "label",
- "div",
- "span",
- "b",
- "i",
- "u",
- "abbr",
- "cite",
- "del",
- "em",
- "ins",
- "kbd",
- "mark",
- "s",
- "samp",
- "sub",
- "sup",
- ]
- ],
Literal[
- "p",
- "label",
- "div",
- "span",
- "b",
- "i",
- "u",
"abbr",
+ "b",
"cite",
"del",
+ "div",
"em",
+ "i",
"ins",
"kbd",
+ "label",
"mark",
+ "p",
"s",
"samp",
+ "span",
"sub",
"sup",
+ "u",
+ ],
+ Var[
+ Literal[
+ "abbr",
+ "b",
+ "cite",
+ "del",
+ "div",
+ "em",
+ "i",
+ "ins",
+ "kbd",
+ "label",
+ "mark",
+ "p",
+ "s",
+ "samp",
+ "span",
+ "sub",
+ "sup",
+ "u",
+ ]
],
]
] = None,
as_child: Optional[Union[Var[bool], bool]] = None,
size: Optional[
Union[
- Var[Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]
+ ],
+ Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ]
+ ],
]
] = None,
weight: Optional[
Union[
- Var[Literal["light", "regular", "medium", "bold"]],
- Literal["light", "regular", "medium", "bold"],
+ Breakpoints[str, Literal["bold", "light", "medium", "regular"]],
+ Literal["bold", "light", "medium", "regular"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["bold", "light", "medium", "regular"]],
+ Literal["bold", "light", "medium", "regular"],
+ ]
+ ],
]
] = None,
align: Optional[
Union[
- Var[Literal["left", "center", "right"]],
- Literal["left", "center", "right"],
+ Breakpoints[str, Literal["center", "left", "right"]],
+ Literal["center", "left", "right"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["center", "left", "right"]],
+ Literal["center", "left", "right"],
+ ]
+ ],
]
] = None,
trim: Optional[
Union[
- Var[Literal["normal", "start", "end", "both"]],
- Literal["normal", "start", "end", "both"],
+ Breakpoints[str, Literal["both", "end", "normal", "start"]],
+ Literal["both", "end", "normal", "start"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["both", "end", "normal", "start"]],
+ Literal["both", "end", "normal", "start"],
+ ]
+ ],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Span":
"""Create a new component instance.
@@ -589,104 +549,58 @@ class Span(Text):
"""
...
-class Em(el.Em, RadixThemesComponent):
+class Em(elements.Em, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Em":
"""Create a new component instance.
@@ -724,7 +638,7 @@ class Em(el.Em, RadixThemesComponent):
"""
...
-class Kbd(el.Kbd, RadixThemesComponent):
+class Kbd(elements.Kbd, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
@@ -732,102 +646,56 @@ class Kbd(el.Kbd, RadixThemesComponent):
*children,
size: Optional[
Union[
- Var[Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]],
]
] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Kbd":
"""Create a new component instance.
@@ -866,105 +734,59 @@ class Kbd(el.Kbd, RadixThemesComponent):
"""
...
-class Quote(el.Q, RadixThemesComponent):
+class Quote(elements.Q, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- cite: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ cite: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Quote":
"""Create a new component instance.
@@ -1003,104 +825,58 @@ class Quote(el.Q, RadixThemesComponent):
"""
...
-class Strong(el.Strong, RadixThemesComponent):
+class Strong(elements.Strong, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Strong":
"""Create a new component instance.
@@ -1151,229 +927,209 @@ class TextNamespace(ComponentNamespace):
as_child: Optional[Union[Var[bool], bool]] = None,
as_: Optional[
Union[
- Var[
- Literal[
- "p",
- "label",
- "div",
- "span",
- "b",
- "i",
- "u",
- "abbr",
- "cite",
- "del",
- "em",
- "ins",
- "kbd",
- "mark",
- "s",
- "samp",
- "sub",
- "sup",
- ]
- ],
Literal[
- "p",
- "label",
- "div",
- "span",
- "b",
- "i",
- "u",
"abbr",
+ "b",
"cite",
"del",
+ "div",
"em",
+ "i",
"ins",
"kbd",
+ "label",
"mark",
+ "p",
"s",
"samp",
+ "span",
"sub",
"sup",
+ "u",
+ ],
+ Var[
+ Literal[
+ "abbr",
+ "b",
+ "cite",
+ "del",
+ "div",
+ "em",
+ "i",
+ "ins",
+ "kbd",
+ "label",
+ "mark",
+ "p",
+ "s",
+ "samp",
+ "span",
+ "sub",
+ "sup",
+ "u",
+ ]
],
]
] = None,
size: Optional[
Union[
- Var[Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]],
+ Breakpoints[str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]],
Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ Var[
+ Union[
+ Breakpoints[
+ str, Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"]
+ ],
+ Literal["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ ]
+ ],
]
] = None,
weight: Optional[
Union[
- Var[Literal["light", "regular", "medium", "bold"]],
- Literal["light", "regular", "medium", "bold"],
+ Breakpoints[str, Literal["bold", "light", "medium", "regular"]],
+ Literal["bold", "light", "medium", "regular"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["bold", "light", "medium", "regular"]],
+ Literal["bold", "light", "medium", "regular"],
+ ]
+ ],
]
] = None,
align: Optional[
Union[
- Var[Literal["left", "center", "right"]],
- Literal["left", "center", "right"],
+ Breakpoints[str, Literal["center", "left", "right"]],
+ Literal["center", "left", "right"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["center", "left", "right"]],
+ Literal["center", "left", "right"],
+ ]
+ ],
]
] = None,
trim: Optional[
Union[
- Var[Literal["normal", "start", "end", "both"]],
- Literal["normal", "start", "end", "both"],
+ Breakpoints[str, Literal["both", "end", "normal", "start"]],
+ Literal["both", "end", "normal", "start"],
+ Var[
+ Union[
+ Breakpoints[str, Literal["both", "end", "normal", "start"]],
+ Literal["both", "end", "normal", "start"],
+ ]
+ ],
]
] = None,
color_scheme: Optional[
Union[
- Var[
- Literal[
- "tomato",
- "red",
- "ruby",
- "crimson",
- "pink",
- "plum",
- "purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
- "sky",
- "mint",
- "lime",
- "yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
- ]
- ],
Literal[
- "tomato",
- "red",
- "ruby",
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
"crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
"pink",
"plum",
"purple",
- "violet",
- "iris",
- "indigo",
- "blue",
- "cyan",
- "teal",
- "jade",
- "green",
- "grass",
- "brown",
- "orange",
+ "red",
+ "ruby",
"sky",
- "mint",
- "lime",
+ "teal",
+ "tomato",
+ "violet",
"yellow",
- "amber",
- "gold",
- "bronze",
- "gray",
+ ],
+ Var[
+ Literal[
+ "amber",
+ "blue",
+ "bronze",
+ "brown",
+ "crimson",
+ "cyan",
+ "gold",
+ "grass",
+ "gray",
+ "green",
+ "indigo",
+ "iris",
+ "jade",
+ "lime",
+ "mint",
+ "orange",
+ "pink",
+ "plum",
+ "purple",
+ "red",
+ "ruby",
+ "sky",
+ "teal",
+ "tomato",
+ "violet",
+ "yellow",
+ ]
],
]
] = None,
high_contrast: Optional[Union[Var[bool], bool]] = None,
- access_key: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
auto_capitalize: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
content_editable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
context_menu: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- dir: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- draggable: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
enter_key_hint: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- hidden: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- input_mode: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- item_prop: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- lang: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- role: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- slot: Optional[Union[Var[Union[str, int, bool]], Union[str, int, bool]]] = None,
- spell_check: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- tab_index: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
- ] = None,
- title: Optional[
- Union[Var[Union[str, int, bool]], Union[str, int, bool]]
+ Union[Var[Union[bool, int, str]], bool, int, str]
] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Text":
"""Create a new component instance.
diff --git a/reflex/components/react_player/__init__.py b/reflex/components/react_player/__init__.py
index 8c4a4486f..3f807b1a0 100644
--- a/reflex/components/react_player/__init__.py
+++ b/reflex/components/react_player/__init__.py
@@ -1,5 +1,6 @@
"""React Player component for audio and video."""
+from . import react_player
from .audio import Audio
from .video import Video
diff --git a/reflex/components/react_player/audio.py b/reflex/components/react_player/audio.py
index 359f37b74..49a5aa31e 100644
--- a/reflex/components/react_player/audio.py
+++ b/reflex/components/react_player/audio.py
@@ -1,4 +1,5 @@
"""A audio component."""
+
from reflex.components.react_player.react_player import ReactPlayer
diff --git a/reflex/components/react_player/audio.pyi b/reflex/components/react_player/audio.pyi
index 07591a185..5c8cc85df 100644
--- a/reflex/components/react_player/audio.pyi
+++ b/reflex/components/react_player/audio.pyi
@@ -1,13 +1,15 @@
"""Stub file for reflex/components/react_player/audio.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
+import reflex
from reflex.components.react_player.react_player import ReactPlayer
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
class Audio(ReactPlayer):
pass
@@ -32,52 +34,40 @@ class Audio(ReactPlayer):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
+ on_blur: Optional[EventType[[]]] = None,
+ on_buffer: Optional[EventType[[]]] = None,
+ on_buffer_end: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_click_preview: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_disable_pip: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_duration: Optional[EventType[float]] = None,
+ on_enable_pip: Optional[EventType[[]]] = None,
+ on_ended: Optional[EventType[[]]] = None,
+ on_error: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_pause: Optional[EventType[[]]] = None,
+ on_play: Optional[EventType[[]]] = None,
+ on_playback_quality_change: Optional[EventType[[]]] = None,
+ on_playback_rate_change: Optional[EventType[[]]] = None,
+ on_progress: Optional[
+ EventType[reflex.components.react_player.react_player.Progress]
] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_ready: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_seek: Optional[EventType[float]] = None,
+ on_start: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Audio":
"""Create the component.
@@ -92,6 +82,22 @@ class Audio(ReactPlayer):
muted: Mutes the player
width: Set the width of the player: ex:640px
height: Set the height of the player: ex:640px
+ on_ready: Called when media is loaded and ready to play. If playing is set to true, media will play immediately.
+ on_start: Called when media starts playing.
+ on_play: Called when media starts or resumes playing after pausing or buffering.
+ on_progress: Callback containing played and loaded progress as a fraction, and playedSeconds and loadedSeconds in seconds. eg { played: 0.12, playedSeconds: 11.3, loaded: 0.34, loadedSeconds: 16.7 }
+ on_duration: Callback containing duration of the media, in seconds.
+ on_pause: Called when media is paused.
+ on_buffer: Called when media starts buffering.
+ on_buffer_end: Called when media has finished buffering. Works for files, YouTube and Facebook.
+ on_seek: Called when media seeks with seconds parameter.
+ on_playback_rate_change: Called when playback rate of the player changed. Only supported by YouTube, Vimeo (if enabled), Wistia, and file paths.
+ on_playback_quality_change: Called when playback quality of the player changed. Only supported by YouTube (if enabled).
+ on_ended: Called when media finishes playing. Does not fire when loop is set to true.
+ on_error: Called when an error occurs whilst attempting to play media.
+ on_click_preview: Called when user clicks the light mode preview.
+ on_enable_pip: Called when picture-in-picture mode is enabled.
+ on_disable_pip: Called when picture-in-picture mode is disabled.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
diff --git a/reflex/components/react_player/react_player.py b/reflex/components/react_player/react_player.py
index 2e09d4bf9..b2c58b754 100644
--- a/reflex/components/react_player/react_player.py
+++ b/reflex/components/react_player/react_player.py
@@ -2,8 +2,20 @@
from __future__ import annotations
+from typing_extensions import TypedDict
+
from reflex.components.component import NoSSRComponent
-from reflex.vars import Var
+from reflex.event import EventHandler, empty_event, identity_event
+from reflex.vars.base import Var
+
+
+class Progress(TypedDict):
+ """Callback containing played and loaded progress as a fraction, and playedSeconds and loadedSeconds in seconds."""
+
+ played: float
+ playedSeconds: float
+ loaded: float
+ loadedSeconds: float
class ReactPlayer(NoSSRComponent):
@@ -11,7 +23,7 @@ class ReactPlayer(NoSSRComponent):
reference: https://github.com/cookpete/react-player.
"""
- library = "react-player@2.12.0"
+ library = "react-player@2.16.0"
tag = "ReactPlayer"
@@ -43,3 +55,51 @@ class ReactPlayer(NoSSRComponent):
# Set the height of the player: ex:640px
height: Var[str]
+
+ # Called when media is loaded and ready to play. If playing is set to true, media will play immediately.
+ on_ready: EventHandler[empty_event]
+
+ # Called when media starts playing.
+ on_start: EventHandler[empty_event]
+
+ # Called when media starts or resumes playing after pausing or buffering.
+ on_play: EventHandler[empty_event]
+
+ # Callback containing played and loaded progress as a fraction, and playedSeconds and loadedSeconds in seconds. eg { played: 0.12, playedSeconds: 11.3, loaded: 0.34, loadedSeconds: 16.7 }
+ on_progress: EventHandler[identity_event(Progress)]
+
+ # Callback containing duration of the media, in seconds.
+ on_duration: EventHandler[identity_event(float)]
+
+ # Called when media is paused.
+ on_pause: EventHandler[empty_event]
+
+ # Called when media starts buffering.
+ on_buffer: EventHandler[empty_event]
+
+ # Called when media has finished buffering. Works for files, YouTube and Facebook.
+ on_buffer_end: EventHandler[empty_event]
+
+ # Called when media seeks with seconds parameter.
+ on_seek: EventHandler[identity_event(float)]
+
+ # Called when playback rate of the player changed. Only supported by YouTube, Vimeo (if enabled), Wistia, and file paths.
+ on_playback_rate_change: EventHandler[empty_event]
+
+ # Called when playback quality of the player changed. Only supported by YouTube (if enabled).
+ on_playback_quality_change: EventHandler[empty_event]
+
+ # Called when media finishes playing. Does not fire when loop is set to true.
+ on_ended: EventHandler[empty_event]
+
+ # Called when an error occurs whilst attempting to play media.
+ on_error: EventHandler[empty_event]
+
+ # Called when user clicks the light mode preview.
+ on_click_preview: EventHandler[empty_event]
+
+ # Called when picture-in-picture mode is enabled.
+ on_enable_pip: EventHandler[empty_event]
+
+ # Called when picture-in-picture mode is disabled.
+ on_disable_pip: EventHandler[empty_event]
diff --git a/reflex/components/react_player/react_player.pyi b/reflex/components/react_player/react_player.pyi
index 16f988460..ebae93f71 100644
--- a/reflex/components/react_player/react_player.pyi
+++ b/reflex/components/react_player/react_player.pyi
@@ -1,14 +1,22 @@
"""Stub file for reflex/components/react_player/react_player.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Union, overload
+
+from typing_extensions import TypedDict
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
from reflex.components.component import NoSSRComponent
-from reflex.vars import Var
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
+
+class Progress(TypedDict):
+ played: float
+ playedSeconds: float
+ loaded: float
+ loadedSeconds: float
class ReactPlayer(NoSSRComponent):
@overload
@@ -31,52 +39,38 @@ class ReactPlayer(NoSSRComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_buffer: Optional[EventType[[]]] = None,
+ on_buffer_end: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_click_preview: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_disable_pip: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_duration: Optional[EventType[float]] = None,
+ on_enable_pip: Optional[EventType[[]]] = None,
+ on_ended: Optional[EventType[[]]] = None,
+ on_error: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_pause: Optional[EventType[[]]] = None,
+ on_play: Optional[EventType[[]]] = None,
+ on_playback_quality_change: Optional[EventType[[]]] = None,
+ on_playback_rate_change: Optional[EventType[[]]] = None,
+ on_progress: Optional[EventType[Progress]] = None,
+ on_ready: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_seek: Optional[EventType[float]] = None,
+ on_start: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ReactPlayer":
"""Create the component.
@@ -91,6 +85,22 @@ class ReactPlayer(NoSSRComponent):
muted: Mutes the player
width: Set the width of the player: ex:640px
height: Set the height of the player: ex:640px
+ on_ready: Called when media is loaded and ready to play. If playing is set to true, media will play immediately.
+ on_start: Called when media starts playing.
+ on_play: Called when media starts or resumes playing after pausing or buffering.
+ on_progress: Callback containing played and loaded progress as a fraction, and playedSeconds and loadedSeconds in seconds. eg { played: 0.12, playedSeconds: 11.3, loaded: 0.34, loadedSeconds: 16.7 }
+ on_duration: Callback containing duration of the media, in seconds.
+ on_pause: Called when media is paused.
+ on_buffer: Called when media starts buffering.
+ on_buffer_end: Called when media has finished buffering. Works for files, YouTube and Facebook.
+ on_seek: Called when media seeks with seconds parameter.
+ on_playback_rate_change: Called when playback rate of the player changed. Only supported by YouTube, Vimeo (if enabled), Wistia, and file paths.
+ on_playback_quality_change: Called when playback quality of the player changed. Only supported by YouTube (if enabled).
+ on_ended: Called when media finishes playing. Does not fire when loop is set to true.
+ on_error: Called when an error occurs whilst attempting to play media.
+ on_click_preview: Called when user clicks the light mode preview.
+ on_enable_pip: Called when picture-in-picture mode is enabled.
+ on_disable_pip: Called when picture-in-picture mode is disabled.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
diff --git a/reflex/components/react_player/video.py b/reflex/components/react_player/video.py
index 834d1a9ae..0823bfbb5 100644
--- a/reflex/components/react_player/video.py
+++ b/reflex/components/react_player/video.py
@@ -1,4 +1,5 @@
"""A video component."""
+
from reflex.components.react_player.react_player import ReactPlayer
diff --git a/reflex/components/react_player/video.pyi b/reflex/components/react_player/video.pyi
index 4c54b241b..4a6bb81b3 100644
--- a/reflex/components/react_player/video.pyi
+++ b/reflex/components/react_player/video.pyi
@@ -1,13 +1,15 @@
"""Stub file for reflex/components/react_player/video.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
+import reflex
from reflex.components.react_player.react_player import ReactPlayer
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
class Video(ReactPlayer):
pass
@@ -32,52 +34,40 @@ class Video(ReactPlayer):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
+ on_blur: Optional[EventType[[]]] = None,
+ on_buffer: Optional[EventType[[]]] = None,
+ on_buffer_end: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_click_preview: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_disable_pip: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_duration: Optional[EventType[float]] = None,
+ on_enable_pip: Optional[EventType[[]]] = None,
+ on_ended: Optional[EventType[[]]] = None,
+ on_error: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_pause: Optional[EventType[[]]] = None,
+ on_play: Optional[EventType[[]]] = None,
+ on_playback_quality_change: Optional[EventType[[]]] = None,
+ on_playback_rate_change: Optional[EventType[[]]] = None,
+ on_progress: Optional[
+ EventType[reflex.components.react_player.react_player.Progress]
] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_ready: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_seek: Optional[EventType[float]] = None,
+ on_start: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Video":
"""Create the component.
@@ -92,6 +82,22 @@ class Video(ReactPlayer):
muted: Mutes the player
width: Set the width of the player: ex:640px
height: Set the height of the player: ex:640px
+ on_ready: Called when media is loaded and ready to play. If playing is set to true, media will play immediately.
+ on_start: Called when media starts playing.
+ on_play: Called when media starts or resumes playing after pausing or buffering.
+ on_progress: Callback containing played and loaded progress as a fraction, and playedSeconds and loadedSeconds in seconds. eg { played: 0.12, playedSeconds: 11.3, loaded: 0.34, loadedSeconds: 16.7 }
+ on_duration: Callback containing duration of the media, in seconds.
+ on_pause: Called when media is paused.
+ on_buffer: Called when media starts buffering.
+ on_buffer_end: Called when media has finished buffering. Works for files, YouTube and Facebook.
+ on_seek: Called when media seeks with seconds parameter.
+ on_playback_rate_change: Called when playback rate of the player changed. Only supported by YouTube, Vimeo (if enabled), Wistia, and file paths.
+ on_playback_quality_change: Called when playback quality of the player changed. Only supported by YouTube (if enabled).
+ on_ended: Called when media finishes playing. Does not fire when loop is set to true.
+ on_error: Called when an error occurs whilst attempting to play media.
+ on_click_preview: Called when user clicks the light mode preview.
+ on_enable_pip: Called when picture-in-picture mode is enabled.
+ on_disable_pip: Called when picture-in-picture mode is disabled.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
diff --git a/reflex/components/recharts/__init__.py b/reflex/components/recharts/__init__.py
index 327b9b326..5e9e6fc14 100644
--- a/reflex/components/recharts/__init__.py
+++ b/reflex/components/recharts/__init__.py
@@ -1,108 +1,119 @@
"""Recharts components."""
-from .cartesian import (
- Area,
- Bar,
- Brush,
- Cartesian,
- CartesianAxis,
- CartesianGrid,
- ErrorBar,
- Funnel,
- Line,
- ReferenceArea,
- ReferenceDot,
- ReferenceLine,
- Scatter,
- XAxis,
- YAxis,
- ZAxis,
+from __future__ import annotations
+
+from reflex.utils import lazy_loader
+
+_SUBMOD_ATTRS: dict = {
+ "cartesian": [
+ "area",
+ "Area",
+ "bar",
+ "Bar",
+ "line",
+ "Line",
+ "scatter",
+ "Scatter",
+ "x_axis",
+ "XAxis",
+ "y_axis",
+ "YAxis",
+ "z_axis",
+ "ZAxis",
+ "brush",
+ "Brush",
+ "cartesian_axis",
+ "CartesianAxis",
+ "cartesian_grid",
+ "CartesianGrid",
+ "reference_line",
+ "ReferenceLine",
+ "reference_dot",
+ "ReferenceDot",
+ "reference_area",
+ "ReferenceArea",
+ "error_bar",
+ "ErrorBar",
+ "funnel",
+ "Funnel",
+ ],
+ "charts": [
+ "area_chart",
+ "AreaChart",
+ "bar_chart",
+ "BarChart",
+ "line_chart",
+ "LineChart",
+ "composed_chart",
+ "ComposedChart",
+ "pie_chart",
+ "PieChart",
+ "radar_chart",
+ "RadarChart",
+ "radial_bar_chart",
+ "RadialBarChart",
+ "scatter_chart",
+ "ScatterChart",
+ "funnel_chart",
+ "FunnelChart",
+ "treemap",
+ "Treemap",
+ ],
+ "general": [
+ "responsive_container",
+ "ResponsiveContainer",
+ "legend",
+ "Legend",
+ "graphing_tooltip",
+ "GraphingTooltip",
+ "label",
+ "Label",
+ "label_list",
+ "LabelList",
+ ],
+ "polar": [
+ "pie",
+ "Pie",
+ "radar",
+ "Radar",
+ "radial_bar",
+ "RadialBar",
+ "polar_angle_axis",
+ "PolarAngleAxis",
+ "polar_grid",
+ "PolarGrid",
+ "polar_radius_axis",
+ "PolarRadiusAxis",
+ ],
+ "recharts": [
+ "LiteralAnimationEasing",
+ "LiteralAreaType",
+ "LiteralAxisType",
+ "LiteralBarChartStackOffset",
+ "LiteralComposedChartBaseValue",
+ "LiteralDirection",
+ "LiteralGridType",
+ "LiteralIconType",
+ "LiteralIfOverflow",
+ "LiteralInterval",
+ "LiteralLayout",
+ "LiteralLegendAlign",
+ "LiteralLegendType",
+ "LiteralLineType",
+ "LiteralOrientation",
+ "LiteralOrientationLeftRightMiddle",
+ "LiteralOrientationTopBottom",
+ "LiteralOrientationTopBottomLeftRight",
+ "LiteralPolarRadiusType",
+ "LiteralScale",
+ "LiteralShape",
+ "LiteralStackOffset",
+ "LiteralSyncMethod",
+ "LiteralVerticalAlign",
+ ],
+}
+
+__getattr__, __dir__, __all__ = lazy_loader.attach(
+ __name__,
+ submod_attrs=_SUBMOD_ATTRS,
)
-from .charts import (
- AreaChart,
- BarChart,
- ComposedChart,
- FunnelChart,
- LineChart,
- PieChart,
- RadarChart,
- RadialBarChart,
- ScatterChart,
- Treemap,
-)
-from .general import GraphingTooltip, Label, LabelList, Legend, ResponsiveContainer
-from .polar import (
- Pie,
- PolarAngleAxis,
- PolarGrid,
- PolarRadiusAxis,
- Radar,
- RadialBar,
-)
-from .recharts import (
- LiteralAnimationEasing,
- LiteralAreaType,
- LiteralAxisType,
- LiteralBarChartStackOffset,
- LiteralComposedChartBaseValue,
- LiteralDirection,
- LiteralGridType,
- LiteralIconType,
- LiteralIfOverflow,
- LiteralInterval,
- LiteralLayout,
- LiteralLegendAlign,
- LiteralLegendType,
- LiteralLineType,
- LiteralOrientation,
- LiteralOrientationLeftRightMiddle,
- LiteralOrientationTopBottom,
- LiteralOrientationTopBottomLeftRight,
- LiteralPolarRadiusType,
- LiteralScale,
- LiteralShape,
- LiteralStackOffset,
- LiteralSyncMethod,
- LiteralVerticalAlign,
-)
-
-area_chart = AreaChart.create
-bar_chart = BarChart.create
-line_chart = LineChart.create
-composed_chart = ComposedChart.create
-pie_chart = PieChart.create
-radar_chart = RadarChart.create
-radial_bar_chart = RadialBarChart.create
-scatter_chart = ScatterChart.create
-funnel_chart = FunnelChart.create
-treemap = Treemap.create
-
-
-area = Area.create
-bar = Bar.create
-line = Line.create
-scatter = Scatter.create
-x_axis = XAxis.create
-y_axis = YAxis.create
-z_axis = ZAxis.create
-brush = Brush.create
-cartesian_axis = CartesianAxis.create
-cartesian_grid = CartesianGrid.create
-reference_line = ReferenceLine.create
-reference_dot = ReferenceDot.create
-reference_area = ReferenceArea.create
-error_bar = ErrorBar.create
-funnel = Funnel.create
-
-responsive_container = ResponsiveContainer.create
-legend = Legend.create
-graphing_tooltip = GraphingTooltip.create
-label = Label.create
-label_list = LabelList.create
-
-pie = Pie.create
-radar = Radar.create
-radial_bar = RadialBar.create
-polar_angle_axis = PolarAngleAxis.create
-polar_grid = PolarGrid.create
-polar_radius_axis = PolarRadiusAxis.create
diff --git a/reflex/components/recharts/__init__.pyi b/reflex/components/recharts/__init__.pyi
new file mode 100644
index 000000000..8f6c4673f
--- /dev/null
+++ b/reflex/components/recharts/__init__.pyi
@@ -0,0 +1,105 @@
+"""Stub file for reflex/components/recharts/__init__.py"""
+# ------------------- DO NOT EDIT ----------------------
+# This file was generated by `reflex/utils/pyi_generator.py`!
+# ------------------------------------------------------
+
+from .cartesian import Area as Area
+from .cartesian import Bar as Bar
+from .cartesian import Brush as Brush
+from .cartesian import CartesianAxis as CartesianAxis
+from .cartesian import CartesianGrid as CartesianGrid
+from .cartesian import ErrorBar as ErrorBar
+from .cartesian import Funnel as Funnel
+from .cartesian import Line as Line
+from .cartesian import ReferenceArea as ReferenceArea
+from .cartesian import ReferenceDot as ReferenceDot
+from .cartesian import ReferenceLine as ReferenceLine
+from .cartesian import Scatter as Scatter
+from .cartesian import XAxis as XAxis
+from .cartesian import YAxis as YAxis
+from .cartesian import ZAxis as ZAxis
+from .cartesian import area as area
+from .cartesian import bar as bar
+from .cartesian import brush as brush
+from .cartesian import cartesian_axis as cartesian_axis
+from .cartesian import cartesian_grid as cartesian_grid
+from .cartesian import error_bar as error_bar
+from .cartesian import funnel as funnel
+from .cartesian import line as line
+from .cartesian import reference_area as reference_area
+from .cartesian import reference_dot as reference_dot
+from .cartesian import reference_line as reference_line
+from .cartesian import scatter as scatter
+from .cartesian import x_axis as x_axis
+from .cartesian import y_axis as y_axis
+from .cartesian import z_axis as z_axis
+from .charts import AreaChart as AreaChart
+from .charts import BarChart as BarChart
+from .charts import ComposedChart as ComposedChart
+from .charts import FunnelChart as FunnelChart
+from .charts import LineChart as LineChart
+from .charts import PieChart as PieChart
+from .charts import RadarChart as RadarChart
+from .charts import RadialBarChart as RadialBarChart
+from .charts import ScatterChart as ScatterChart
+from .charts import Treemap as Treemap
+from .charts import area_chart as area_chart
+from .charts import bar_chart as bar_chart
+from .charts import composed_chart as composed_chart
+from .charts import funnel_chart as funnel_chart
+from .charts import line_chart as line_chart
+from .charts import pie_chart as pie_chart
+from .charts import radar_chart as radar_chart
+from .charts import radial_bar_chart as radial_bar_chart
+from .charts import scatter_chart as scatter_chart
+from .charts import treemap as treemap
+from .general import GraphingTooltip as GraphingTooltip
+from .general import Label as Label
+from .general import LabelList as LabelList
+from .general import Legend as Legend
+from .general import ResponsiveContainer as ResponsiveContainer
+from .general import graphing_tooltip as graphing_tooltip
+from .general import label as label
+from .general import label_list as label_list
+from .general import legend as legend
+from .general import responsive_container as responsive_container
+from .polar import Pie as Pie
+from .polar import PolarAngleAxis as PolarAngleAxis
+from .polar import PolarGrid as PolarGrid
+from .polar import PolarRadiusAxis as PolarRadiusAxis
+from .polar import Radar as Radar
+from .polar import RadialBar as RadialBar
+from .polar import pie as pie
+from .polar import polar_angle_axis as polar_angle_axis
+from .polar import polar_grid as polar_grid
+from .polar import polar_radius_axis as polar_radius_axis
+from .polar import radar as radar
+from .polar import radial_bar as radial_bar
+from .recharts import LiteralAnimationEasing as LiteralAnimationEasing
+from .recharts import LiteralAreaType as LiteralAreaType
+from .recharts import LiteralAxisType as LiteralAxisType
+from .recharts import LiteralBarChartStackOffset as LiteralBarChartStackOffset
+from .recharts import LiteralComposedChartBaseValue as LiteralComposedChartBaseValue
+from .recharts import LiteralDirection as LiteralDirection
+from .recharts import LiteralGridType as LiteralGridType
+from .recharts import LiteralIconType as LiteralIconType
+from .recharts import LiteralIfOverflow as LiteralIfOverflow
+from .recharts import LiteralInterval as LiteralInterval
+from .recharts import LiteralLayout as LiteralLayout
+from .recharts import LiteralLegendAlign as LiteralLegendAlign
+from .recharts import LiteralLegendType as LiteralLegendType
+from .recharts import LiteralLineType as LiteralLineType
+from .recharts import LiteralOrientation as LiteralOrientation
+from .recharts import (
+ LiteralOrientationLeftRightMiddle as LiteralOrientationLeftRightMiddle,
+)
+from .recharts import LiteralOrientationTopBottom as LiteralOrientationTopBottom
+from .recharts import (
+ LiteralOrientationTopBottomLeftRight as LiteralOrientationTopBottomLeftRight,
+)
+from .recharts import LiteralPolarRadiusType as LiteralPolarRadiusType
+from .recharts import LiteralScale as LiteralScale
+from .recharts import LiteralShape as LiteralShape
+from .recharts import LiteralStackOffset as LiteralStackOffset
+from .recharts import LiteralSyncMethod as LiteralSyncMethod
+from .recharts import LiteralVerticalAlign as LiteralVerticalAlign
diff --git a/reflex/components/recharts/cartesian.py b/reflex/components/recharts/cartesian.py
index 136bddf9f..865b50a32 100644
--- a/reflex/components/recharts/cartesian.py
+++ b/reflex/components/recharts/cartesian.py
@@ -1,10 +1,13 @@
"""Cartesian charts in Recharts."""
+
from __future__ import annotations
from typing import Any, Dict, List, Union
from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.constants.colors import Color
+from reflex.event import EventHandler, empty_event
+from reflex.vars.base import LiteralVar, Var
from .recharts import (
LiteralAnimationEasing,
@@ -12,13 +15,17 @@ from .recharts import (
LiteralDirection,
LiteralIfOverflow,
LiteralInterval,
+ LiteralIntervalAxis,
LiteralLayout,
+ LiteralLegendType,
LiteralLineType,
+ LiteralOrientationLeftRight,
LiteralOrientationTopBottom,
LiteralOrientationTopBottomLeftRight,
LiteralPolarRadiusType,
LiteralScale,
LiteralShape,
+ LiteralTextAnchor,
Recharts,
)
@@ -26,40 +33,49 @@ from .recharts import (
class Axis(Recharts):
"""A base class for axes in Recharts."""
- # The key of a group of data which should be unique in an area chart.
+ # The key of data displayed in the axis.
data_key: Var[Union[str, int]]
- # If set true, the axis do not display in the chart.
+ # If set true, the axis do not display in the chart. Default: False
hide: Var[bool]
- # The orientation of axis 'top' | 'bottom'
- orientation: Var[LiteralOrientationTopBottom]
+ # The width of axis which is usually calculated internally.
+ width: Var[Union[str, int]]
+
+ # The height of axis, which can be setted by user.
+ height: Var[Union[str, int]]
# The type of axis 'number' | 'category'
type_: Var[LiteralPolarRadiusType]
- # Allow the ticks of XAxis to be decimals or not.
+ # If set 0, all the ticks will be shown. If set preserveStart", "preserveEnd" or "preserveStartEnd", the ticks which is to be shown or hidden will be calculated automatically. Default: "preserveEnd"
+ interval: Var[Union[LiteralIntervalAxis, int]]
+
+ # Allow the ticks of Axis to be decimals or not. Default: True
allow_decimals: Var[bool]
- # When domain of the axis is specified and the type of the axis is 'number', if allowDataOverflow is set to be false, the domain will be adjusted when the minimum value of data is smaller than domain[0] or the maximum value of data is greater than domain[1] so that the axis displays all data values. If set to true, graphic elements (line, area, bars) will be clipped to conform to the specified domain.
+ # When domain of the axis is specified and the type of the axis is 'number', if allowDataOverflow is set to be false, the domain will be adjusted when the minimum value of data is smaller than domain[0] or the maximum value of data is greater than domain[1] so that the axis displays all data values. If set to true, graphic elements (line, area, bars) will be clipped to conform to the specified domain. Default: False
allow_data_overflow: Var[bool]
- # Allow the axis has duplicated categorys or not when the type of axis is "category".
+ # Allow the axis has duplicated categorys or not when the type of axis is "category". Default: True
allow_duplicated_category: Var[bool]
- # If set false, no axis line will be drawn. If set a object, the option is the configuration of axis line.
+ # The range of the axis. Work best in conjuction with allow_data_overflow. Default: [0, "auto"]
+ domain: Var[List]
+
+ # If set false, no axis line will be drawn. Default: True
axis_line: Var[bool]
- # If set false, no axis tick lines will be drawn. If set a object, the option is the configuration of tick lines.
- tick_line: Var[bool]
-
- # If set true, flips ticks around the axis line, displaying the labels inside the chart instead of outside.
+ # If set true, flips ticks around the axis line, displaying the labels inside the chart instead of outside. Default: False
mirror: Var[bool]
- # Reverse the ticks or not.
+ # Reverse the ticks or not. Default: False
reversed: Var[bool]
- # If 'auto' set, the scale function is decided by the type of chart, and the props type. 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utc' | 'sequential' | 'threshold' | Function
+ # The label of axis, which appears next to the axis.
+ label: Var[Union[str, int, Dict[str, Any]]]
+
+ # If 'auto' set, the scale function is decided by the type of chart, and the props type. 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utc' | 'sequential' | 'threshold'. Default: "auto"
scale: Var[LiteralScale]
# The unit of data displayed in the axis. This option will be used to represent an index unit in a scatter chart.
@@ -68,20 +84,50 @@ class Axis(Recharts):
# The name of data displayed in the axis. This option will be used to represent an index in a scatter chart.
name: Var[Union[str, int]]
- def get_event_triggers(self) -> dict[str, Union[Var, Any]]:
- """Get the event triggers that pass the component's value to the handler.
+ # Set the values of axis ticks manually.
+ ticks: Var[List[Union[str, int]]]
- Returns:
- A dict mapping the event trigger to the var that is passed to the handler.
- """
- return {
- EventTriggers.ON_CLICK: lambda: [],
- EventTriggers.ON_MOUSE_MOVE: lambda: [],
- EventTriggers.ON_MOUSE_OVER: lambda: [],
- EventTriggers.ON_MOUSE_OUT: lambda: [],
- EventTriggers.ON_MOUSE_ENTER: lambda: [],
- EventTriggers.ON_MOUSE_LEAVE: lambda: [],
- }
+ # If set false, no ticks will be drawn.
+ tick: Var[bool]
+
+ # The count of axis ticks. Not used if 'type' is 'category'. Default: 5
+ tick_count: Var[int]
+
+ # If set false, no axis tick lines will be drawn. Default: True
+ tick_line: Var[bool]
+
+ # The length of tick line. Default: 6
+ tick_size: Var[int]
+
+ # The minimum gap between two adjacent labels. Default: 5
+ min_tick_gap: Var[int]
+
+ # The stroke color of axis. Default: rx.color("gray", 9)
+ stroke: Var[Union[str, Color]] = LiteralVar.create(Color("gray", 9))
+
+ # The text anchor of axis. Default: "middle"
+ text_anchor: Var[LiteralTextAnchor]
+
+ # The customized event handler of click on the ticks of this axis
+ on_click: EventHandler[empty_event]
+
+ # The customized event handler of mousedown on the ticks of this axis
+ on_mouse_down: EventHandler[empty_event]
+
+ # The customized event handler of mouseup on the ticks of this axis
+ on_mouse_up: EventHandler[empty_event]
+
+ # The customized event handler of mousemove on the ticks of this axis
+ on_mouse_move: EventHandler[empty_event]
+
+ # The customized event handler of mouseout on the ticks of this axis
+ on_mouse_out: EventHandler[empty_event]
+
+ # The customized event handler of mouseenter on the ticks of this axis
+ on_mouse_enter: EventHandler[empty_event]
+
+ # The customized event handler of mouseleave on the ticks of this axis
+ on_mouse_leave: EventHandler[empty_event]
class XAxis(Axis):
@@ -91,6 +137,21 @@ class XAxis(Axis):
alias = "RechartsXAxis"
+ # The orientation of axis 'top' | 'bottom'. Default: "bottom"
+ orientation: Var[LiteralOrientationTopBottom]
+
+ # The id of x-axis which is corresponding to the data. Default: 0
+ x_axis_id: Var[Union[str, int]]
+
+ # Ensures that all datapoints within a chart contribute to its domain calculation, even when they are hidden. Default: False
+ include_hidden: Var[bool]
+
+ # The angle of axis ticks. Default: 0
+ angle: Var[int]
+
+ # Specify the padding of x-axis. Default: {"left": 0, "right": 0}
+ padding: Var[Dict[str, int]]
+
class YAxis(Axis):
"""A YAxis component in Recharts."""
@@ -99,8 +160,14 @@ class YAxis(Axis):
alias = "RechartsYAxis"
- # The key of data displayed in the axis.
- data_key: Var[Union[str, int]]
+ # The orientation of axis 'left' | 'right'. Default: "left"
+ orientation: Var[LiteralOrientationLeftRight]
+
+ # The id of y-axis which is corresponding to the data. Default: 0
+ y_axis_id: Var[Union[str, int]]
+
+ # Specify the padding of y-axis. Default: {"top": 0, "bottom": 0}
+ padding: Var[Dict[str, int]]
class ZAxis(Recharts):
@@ -108,12 +175,15 @@ class ZAxis(Recharts):
tag = "ZAxis"
- alias = "RechartszAxis"
+ alias = "RechartsZAxis"
# The key of data displayed in the axis.
data_key: Var[Union[str, int]]
- # The range of axis.
+ # The unique id of z-axis. Default: 0
+ z_axis_id: Var[Union[str, int]]
+
+ # The range of axis. Default: [10, 10]
range: Var[List[int]]
# The unit of data displayed in the axis. This option will be used to represent an index unit in a scatter chart.
@@ -122,7 +192,7 @@ class ZAxis(Recharts):
# The name of data displayed in the axis. This option will be used to represent an index in a scatter chart.
name: Var[Union[str, int]]
- # If 'auto' set, the scale function is decided by the type of chart, and the props type.
+ # If 'auto' set, the scale function is decided by the type of chart, and the props type. Default: "auto"
scale: Var[LiteralScale]
@@ -133,39 +203,48 @@ class Brush(Recharts):
alias = "RechartsBrush"
- # Stroke color
- stroke: Var[str]
+ # Stroke color. Default: rx.color("gray", 9)
+ stroke: Var[Union[str, Color]] = LiteralVar.create(Color("gray", 9))
+
+ # The fill color of brush. Default: rx.color("gray", 2)
+ fill: Var[Union[str, Color]] = LiteralVar.create(Color("gray", 2))
# The key of data displayed in the axis.
data_key: Var[Union[str, int]]
- # The x-coordinate of brush.
+ # The x-coordinate of brush. Default: 0
x: Var[int]
- # The y-coordinate of brush.
+ # The y-coordinate of brush. Default: 0
y: Var[int]
- # The width of brush.
+ # The width of brush. Default: 0
width: Var[int]
- # The height of brush.
+ # The height of brush. Default: 40
height: Var[int]
- # The data domain of brush, [min, max].
+ # The original data of a LineChart, a BarChart or an AreaChart.
data: Var[List[Any]]
- # The width of each traveller.
+ # The width of each traveller. Default: 5
traveller_width: Var[int]
- # The data with gap of refreshing chart. If the option is not set, the chart will be refreshed every time
+ # The data with gap of refreshing chart. If the option is not set, the chart will be refreshed every time. Default: 1
gap: Var[int]
- # The default start index of brush. If the option is not set, the start index will be 0.
+ # The default start index of brush. If the option is not set, the start index will be 0. Default: 0
start_index: Var[int]
- # The default end index of brush. If the option is not set, the end index will be 1.
+ # The default end index of brush. If the option is not set, the end index will be calculated by the length of data.
end_index: Var[int]
+ # The fill color of brush
+ fill: Var[Union[str, Color]]
+
+ # The stroke color of brush
+ stroke: Var[Union[str, Color]]
+
def get_event_triggers(self) -> dict[str, Union[Var, Any]]:
"""Get the event triggers that pass the component's value to the handler.
@@ -173,7 +252,7 @@ class Brush(Recharts):
A dict mapping the event trigger to the var that is passed to the handler.
"""
return {
- EventTriggers.ON_CHANGE: lambda: [],
+ EventTriggers.ON_CHANGE: empty_event,
}
@@ -186,29 +265,62 @@ class Cartesian(Recharts):
# The key of a group of data which should be unique in an area chart.
data_key: Var[Union[str, int]]
- # The id of x-axis which is corresponding to the data.
+ # The id of x-axis which is corresponding to the data. Default: 0
x_axis_id: Var[Union[str, int]]
- # The id of y-axis which is corresponding to the data.
+ # The id of y-axis which is corresponding to the data. Default: 0
y_axis_id: Var[Union[str, int]]
- # The type of icon in legend. If set to 'none', no legend item will be rendered. 'line' | 'plainline' | 'square' | 'rect'| 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye' | 'none'optional
- # legend_type: Var[LiteralLegendType]
+ # The type of icon in legend. If set to 'none', no legend item will be rendered. 'line' | 'plainline' | 'square' | 'rect'| 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye' | 'none' optional
+ legend_type: Var[LiteralLegendType]
- def get_event_triggers(self) -> dict[str, Union[Var, Any]]:
- """Get the event triggers that pass the component's value to the handler.
+ # If set false, animation of bar will be disabled. Default: True
+ is_animation_active: Var[bool]
- Returns:
- A dict mapping the event trigger to the var that is passed to the handler.
- """
- return {
- EventTriggers.ON_CLICK: lambda: [],
- EventTriggers.ON_MOUSE_MOVE: lambda: [],
- EventTriggers.ON_MOUSE_OVER: lambda: [],
- EventTriggers.ON_MOUSE_OUT: lambda: [],
- EventTriggers.ON_MOUSE_ENTER: lambda: [],
- EventTriggers.ON_MOUSE_LEAVE: lambda: [],
- }
+ # Specifies when the animation should begin, the unit of this option is ms. Default: 0
+ animation_begin: Var[int]
+
+ # Specifies the duration of animation, the unit of this option is ms. Default: 1500
+ animation_duration: Var[int]
+
+ # The type of easing function. Default: "ease"
+ animation_easing: Var[LiteralAnimationEasing]
+
+ # The unit of data. This option will be used in tooltip.
+ unit: Var[Union[str, int]]
+
+ # The name of data. This option will be used in tooltip and legend to represent the component. If no value was set to this option, the value of dataKey will be used alternatively.
+ name: Var[Union[str, int]]
+
+ # The customized event handler of animation start
+ on_animation_start: EventHandler[empty_event]
+
+ # The customized event handler of animation end
+ on_animation_end: EventHandler[empty_event]
+
+ # The customized event handler of click on the component in this group
+ on_click: EventHandler[empty_event]
+
+ # The customized event handler of mousedown on the component in this group
+ on_mouse_down: EventHandler[empty_event]
+
+ # The customized event handler of mouseup on the component in this group
+ on_mouse_up: EventHandler[empty_event]
+
+ # The customized event handler of mousemove on the component in this group
+ on_mouse_move: EventHandler[empty_event]
+
+ # The customized event handler of mouseover on the component in this group
+ on_mouse_over: EventHandler[empty_event]
+
+ # The customized event handler of mouseout on the component in this group
+ on_mouse_out: EventHandler[empty_event]
+
+ # The customized event handler of mouseenter on the component in this group
+ on_mouse_enter: EventHandler[empty_event]
+
+ # The customized event handler of mouseleave on the component in this group
+ on_mouse_leave: EventHandler[empty_event]
class Area(Cartesian):
@@ -218,29 +330,43 @@ class Area(Cartesian):
alias = "RechartsArea"
- # The color of the line stroke.
- stroke: Var[str]
+ # The color of the line stroke. Default: rx.color("accent", 9)
+ stroke: Var[Union[str, Color]] = LiteralVar.create(Color("accent", 9))
- # The width of the line stroke.
+ # The width of the line stroke. Default: 1
stroke_width: Var[int]
- # The color of the area fill.
- fill: Var[str]
+ # The color of the area fill. Default: rx.color("accent", 5)
+ fill: Var[Union[str, Color]] = LiteralVar.create(Color("accent", 5))
- # The interpolation type of area. And customized interpolation function can be set to type. 'basis' | 'basisClosed' | 'basisOpen' | 'bumpX' | 'bumpY' | 'bump' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' |
- type_: Var[LiteralAreaType]
+ # The interpolation type of area. And customized interpolation function can be set to type. 'basis' | 'basisClosed' | 'basisOpen' | 'bumpX' | 'bumpY' | 'bump' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter'. Default: "monotone"
+ type_: Var[LiteralAreaType] = LiteralVar.create("monotone")
- # If false set, dots will not be drawn. If true set, dots will be drawn which have the props calculated internally.
- dot: Var[bool]
+ # If false set, dots will not be drawn. If true set, dots will be drawn which have the props calculated internally. Default: False
+ dot: Var[Union[bool, Dict[str, Any]]]
- # The dot is shown when user enter an area chart and this chart has tooltip. If false set, no active dot will not be drawn. If true set, active dot will be drawn which have the props calculated internally.
- active_dot: Var[bool]
+ # The dot is shown when user enter an area chart and this chart has tooltip. If false set, no active dot will not be drawn. If true set, active dot will be drawn which have the props calculated internally. Default: {stroke: rx.color("accent", 2), fill: rx.color("accent", 10)}
+ active_dot: Var[Union[bool, Dict[str, Any]]] = LiteralVar.create(
+ {
+ "stroke": Color("accent", 2),
+ "fill": Color("accent", 10),
+ }
+ )
- # If false set, labels will not be drawn. If true set, labels will be drawn which have the props calculated internally.
+ # If set false, labels will not be drawn. If set true, labels will be drawn which have the props calculated internally. Default: False
label: Var[bool]
- # The stack id of area, when two areas have the same value axis and same stackId, then the two areas area stacked in order.
- stack_id: Var[str]
+ # The value which can describle the line, usually calculated internally.
+ base_line: Var[Union[str, List[Dict[str, Any]]]]
+
+ # The coordinates of all the points in the area, usually calculated internally.
+ points: Var[List[Dict[str, Any]]]
+
+ # The stack id of area, when two areas have the same value axis and same stack_id, then the two areas are stacked in order.
+ stack_id: Var[Union[str, int]]
+
+ # Whether to connect a graph area across null points. Default: False
+ connect_nulls: Var[bool]
# Valid children components
_valid_children: List[str] = ["LabelList"]
@@ -254,29 +380,44 @@ class Bar(Cartesian):
alias = "RechartsBar"
# The color of the line stroke.
- stroke: Var[str]
+ stroke: Var[Union[str, Color]]
# The width of the line stroke.
stroke_width: Var[int]
- # The width of the line stroke.
- fill: Var[str]
+ # The width of the line stroke. Default: Color("accent", 9)
+ fill: Var[Union[str, Color]] = LiteralVar.create(Color("accent", 9))
- # If false set, background of bars will not be drawn. If true set, background of bars will be drawn which have the props calculated internally.
+ # If false set, background of bars will not be drawn. If true set, background of bars will be drawn which have the props calculated internally. Default: False
background: Var[bool]
- # If false set, labels will not be drawn. If true set, labels will be drawn which have the props calculated internally.
+ # If false set, labels will not be drawn. If true set, labels will be drawn which have the props calculated internally. Default: False
label: Var[bool]
- # The stack id of bar, when two areas have the same value axis and same stackId, then the two areas area stacked in order.
+ # The stack id of bar, when two bars have the same value axis and same stack_id, then the two bars are stacked in order.
stack_id: Var[str]
- # Size of the bar
+ # The unit of data. This option will be used in tooltip.
+ unit: Var[Union[str, int]]
+
+ # The minimal height of a bar in a horizontal BarChart, or the minimal width of a bar in a vertical BarChart. By default, 0 values are not shown. To visualize a 0 (or close to zero) point, set the minimal point size to a pixel value like 3. In stacked bar charts, minPointSize might not be respected for tightly packed values. So we strongly recommend not using this prop in stacked BarCharts.
+ min_point_size: Var[int]
+
+ # The name of data. This option will be used in tooltip and legend to represent a bar. If no value was set to this option, the value of dataKey will be used alternatively.
+ name: Var[Union[str, int]]
+
+ # Size of the bar (if one bar_size is set then a bar_size must be set for all bars)
bar_size: Var[int]
# Max size of the bar
max_bar_size: Var[int]
+ # If set a value, the option is the radius of all the rounded corners. If set a array, the option are in turn the radiuses of top-left corner, top-right corner, bottom-right corner, bottom-left corner. Default: 0
+ radius: Var[Union[int, List[int]]]
+
+ # The active bar is shown when a user enters a bar chart and this chart has tooltip. If set to false, no active bar will be drawn. If set to true, active bar will be drawn with the props calculated internally. If passed an object, active bar will be drawn, and the internally calculated props will be merged with the key value pairs of the passed object.
+ # active_bar: Var[Union[bool, Dict[str, Any]]]
+
# Valid children components
_valid_children: List[str] = ["Cell", "LabelList", "ErrorBar"]
@@ -291,32 +432,51 @@ class Line(Cartesian):
# The interpolation type of line. And customized interpolation function can be set to type. It's the same as type in Area.
type_: Var[LiteralAreaType]
- # The color of the line stroke.
- stroke: Var[str]
+ # The color of the line stroke. Default: rx.color("accent", 9)
+ stroke: Var[Union[str, Color]] = LiteralVar.create(Color("accent", 9))
- # The width of the line stroke.
- stoke_width: Var[int]
+ # The width of the line stroke. Default: 1
+ stroke_width: Var[int]
- # The dot is shown when mouse enter a line chart and this chart has tooltip. If false set, no active dot will not be drawn. If true set, active dot will be drawn which have the props calculated internally.
- dot: Var[bool]
+ # The dot is shown when mouse enter a line chart and this chart has tooltip. If false set, no active dot will not be drawn. If true set, active dot will be drawn which have the props calculated internally. Default: {"stroke": rx.color("accent", 10), "fill": rx.color("accent", 4)}
+ dot: Var[Union[bool, Dict[str, Any]]] = LiteralVar.create(
+ {
+ "stroke": Color("accent", 10),
+ "fill": Color("accent", 4),
+ }
+ )
- # The dot is shown when user enter an area chart and this chart has tooltip. If false set, no active dot will not be drawn. If true set, active dot will be drawn which have the props calculated internally.
- active_dot: Var[bool]
+ # The dot is shown when user enter an area chart and this chart has tooltip. If false set, no active dot will not be drawn. If true set, active dot will be drawn which have the props calculated internally. Default: {"stroke": rx.color("accent", 2), "fill": rx.color("accent", 10)}
+ active_dot: Var[Union[bool, Dict[str, Any]]] = LiteralVar.create(
+ {
+ "stroke": Color("accent", 2),
+ "fill": Color("accent", 10),
+ }
+ )
- # If false set, labels will not be drawn. If true set, labels will be drawn which have the props calculated internally.
+ # If false set, labels will not be drawn. If true set, labels will be drawn which have the props calculated internally. Default: False
label: Var[bool]
- # Hides the line when true, useful when toggling visibility state via legend.
+ # Hides the line when true, useful when toggling visibility state via legend. Default: False
hide: Var[bool]
# Whether to connect a graph line across null points.
connect_nulls: Var[bool]
+ # The unit of data. This option will be used in tooltip.
+ unit: Var[Union[str, int]]
+
+ # The coordinates of all the points in the line, usually calculated internally.
+ points: Var[List[Dict[str, Any]]]
+
+ # The pattern of dashes and gaps used to paint the line.
+ stroke_dasharray: Var[str]
+
# Valid children components
_valid_children: List[str] = ["LabelList", "ErrorBar"]
-class Scatter(Cartesian):
+class Scatter(Recharts):
"""A Scatter component in Recharts."""
tag = "Scatter"
@@ -326,29 +486,71 @@ class Scatter(Cartesian):
# The source data, in which each element is an object.
data: Var[List[Dict[str, Any]]]
- # The id of z-axis which is corresponding to the data.
- z_axis_id: Var[str]
+ # The type of icon in legend. If set to 'none', no legend item will be rendered. 'line' | 'plainline' | 'square' | 'rect'| 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none'. Default: "circle"
+ legend_type: Var[LiteralLegendType]
- # If false set, line will not be drawn. If true set, line will be drawn which have the props calculated internally.
+ # The id of x-axis which is corresponding to the data. Default: 0
+ x_axis_id: Var[Union[str, int]]
+
+ # The id of y-axis which is corresponding to the data. Default: 0
+ y_axis_id: Var[Union[str, int]]
+
+ # The id of z-axis which is corresponding to the data. Default: 0
+ z_axis_id: Var[Union[str, int]]
+
+ # If false set, line will not be drawn. If true set, line will be drawn which have the props calculated internally. Default: False
line: Var[bool]
- # If a string set, specified symbol will be used to show scatter item. 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye'
+ # If a string set, specified symbol will be used to show scatter item. 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye'. Default: "circle"
shape: Var[LiteralShape]
- # If 'joint' set, line will generated by just jointing all the points. If 'fitting' set, line will be generated by fitting algorithm. 'joint' | 'fitting'
+ # If 'joint' set, line will generated by just jointing all the points. If 'fitting' set, line will be generated by fitting algorithm. 'joint' | 'fitting'. Default: "joint"
line_type: Var[LiteralLineType]
- # The fill
- fill: Var[str]
-
- # the name
- name: Var[Union[str, int]]
+ # The fill color of the scatter. Default: rx.color("accent", 9)
+ fill: Var[Union[str, Color]] = LiteralVar.create(Color("accent", 9))
# Valid children components.
_valid_children: List[str] = ["LabelList", "ErrorBar"]
+ # If set false, animation of bar will be disabled. Default: True in CSR, False in SSR
+ is_animation_active: Var[bool]
-class Funnel(Cartesian):
+ # Specifies when the animation should begin, the unit of this option is ms. Default: 0
+ animation_begin: Var[int]
+
+ # Specifies the duration of animation, the unit of this option is ms. Default: 1500
+ animation_duration: Var[int]
+
+ # The type of easing function. Default: "ease"
+ animation_easing: Var[LiteralAnimationEasing]
+
+ # The customized event handler of click on the component in this group
+ on_click: EventHandler[empty_event]
+
+ # The customized event handler of mousedown on the component in this group
+ on_mouse_down: EventHandler[empty_event]
+
+ # The customized event handler of mouseup on the component in this group
+ on_mouse_up: EventHandler[empty_event]
+
+ # The customized event handler of mousemove on the component in this group
+ on_mouse_move: EventHandler[empty_event]
+
+ # The customized event handler of mouseover on the component in this group
+ on_mouse_over: EventHandler[empty_event]
+
+ # The customized event handler of mouseout on the component in this group
+ on_mouse_out: EventHandler[empty_event]
+
+ # The customized event handler of mouseenter on the component in this group
+ on_mouse_enter: EventHandler[empty_event]
+
+ # The customized event handler of mouseleave on the component in this group
+ on_mouse_leave: EventHandler[empty_event]
+
+
+class Funnel(Recharts):
"""A Funnel component in Recharts."""
tag = "Funnel"
@@ -358,18 +560,66 @@ class Funnel(Cartesian):
# The source data, in which each element is an object.
data: Var[List[Dict[str, Any]]]
- # Specifies when the animation should begin, the unit of this option is ms.
+ # The key or getter of a group of data which should be unique in a FunnelChart.
+ data_key: Var[Union[str, int]]
+
+ # The key of each sector's name. Default: "name"
+ name_key: Var[str]
+
+ # The type of icon in legend. If set to 'none', no legend item will be rendered. Default: "line"
+ legend_type: Var[LiteralLegendType]
+
+ # If set false, animation of line will be disabled. Default: True
+ is_animation_active: Var[bool]
+
+ # Specifies when the animation should begin, the unit of this option is ms. Default: 0
animation_begin: Var[int]
- # Specifies the duration of animation, the unit of this option is ms.
+ # Specifies the duration of animation, the unit of this option is ms. Default: 1500
animation_duration: Var[int]
- # The type of easing function. 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'
+ # The type of easing function. 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'. Default "ease"
animation_easing: Var[LiteralAnimationEasing]
+ # Stroke color. Default: rx.color("gray", 3)
+ stroke: Var[Union[str, Color]] = LiteralVar.create(Color("gray", 3))
+
+ # The coordinates of all the trapezoids in the funnel, usually calculated internally.
+ trapezoids: Var[List[Dict[str, Any]]]
+
# Valid children components
_valid_children: List[str] = ["LabelList", "Cell"]
+ # The customized event handler of animation start
+ on_animation_start: EventHandler[empty_event]
+
+ # The customized event handler of animation end
+ on_animation_end: EventHandler[empty_event]
+
+ # The customized event handler of click on the component in this group
+ on_click: EventHandler[empty_event]
+
+ # The customized event handler of mousedown on the component in this group
+ on_mouse_down: EventHandler[empty_event]
+
+ # The customized event handler of mouseup on the component in this group
+ on_mouse_up: EventHandler[empty_event]
+
+ # The customized event handler of mousemove on the component in this group
+ on_mouse_move: EventHandler[empty_event]
+
+ # The customized event handler of mouseover on the component in this group
+ on_mouse_over: EventHandler[empty_event]
+
+ # The customized event handler of mouseout on the component in this group
+ on_mouse_out: EventHandler[empty_event]
+
+ # The customized event handler of mouseenter on the component in this group
+ on_mouse_enter: EventHandler[empty_event]
+
+ # The customized event handler of mouseleave on the component in this group
+ on_mouse_leave: EventHandler[empty_event]
+
class ErrorBar(Recharts):
"""An ErrorBar component in Recharts."""
@@ -378,41 +628,38 @@ class ErrorBar(Recharts):
alias = "RechartsErrorBar"
- # The direction of error bar. 'x' | 'y' | 'both'
+ # Only used for ScatterChart with error bars in two directions. Only accepts a value of "x" or "y" and makes the error bars lie in that direction.
direction: Var[LiteralDirection]
# The key of a group of data which should be unique in an area chart.
data_key: Var[Union[str, int]]
- # The width of the error bar ends.
+ # The width of the error bar ends. Default: 5
width: Var[int]
- # The stroke color of error bar.
- stroke: Var[str]
+ # The stroke color of error bar. Default: rx.color("gray", 8)
+ stroke: Var[Union[str, Color]] = LiteralVar.create(Color("gray", 8))
- # The stroke width of error bar.
- stroke_width: Var[int]
+ # The stroke width of error bar. Default: 1.5
+ stroke_width: Var[Union[int, float]]
class Reference(Recharts):
"""A base class for reference components in Reference."""
- # The id of x-axis which is corresponding to the data.
+ # The id of x-axis which is corresponding to the data. Default: 0
x_axis_id: Var[Union[str, int]]
- # The id of y-axis which is corresponding to the data.
+ # The id of y-axis which is corresponding to the data. Default: 0
y_axis_id: Var[Union[str, int]]
- # If set a string or a number, a vertical line perpendicular to the x-axis specified by xAxisId will be drawn. If the specified x-axis is a number axis, the type of x must be Number. If the specified x-axis is a category axis, the value of x must be one of the categorys, otherwise no line will be drawn.
- x: Var[str]
-
- # If set a string or a number, a horizontal line perpendicular to the y-axis specified by yAxisId will be drawn. If the specified y-axis is a number axis, the type of y must be Number. If the specified y-axis is a category axis, the value of y must be one of the categorys, otherwise no line will be drawn.
- y: Var[str]
-
- # Defines how to draw the reference line if it falls partly outside the canvas. If set to 'discard', the reference line will not be drawn at all. If set to 'hidden', the reference line will be clipped to the canvas. If set to 'visible', the reference line will be drawn completely. If set to 'extendDomain', the domain of the overflown axis will be extended such that the reference line fits into the canvas.
+ # Defines how to draw the reference line if it falls partly outside the canvas. If set to 'discard', the reference line will not be drawn at all. If set to 'hidden', the reference line will be clipped to the canvas. If set to 'visible', the reference line will be drawn completely. If set to 'extendDomain', the domain of the overflown axis will be extended such that the reference line fits into the canvas. Default: "discard"
if_overflow: Var[LiteralIfOverflow]
- # If set true, the line will be rendered in front of bars in BarChart, etc.
+ # If set a string or a number, default label will be drawn, and the option is content.
+ label: Var[Union[str, int]]
+
+ # If set true, the line will be rendered in front of bars in BarChart, etc. Default: False
is_front: Var[bool]
@@ -423,12 +670,24 @@ class ReferenceLine(Reference):
alias = "RechartsReferenceLine"
- # The width of the stroke.
- stroke_width: Var[int]
+ # If set a string or a number, a vertical line perpendicular to the x-axis specified by xAxisId will be drawn. If the specified x-axis is a number axis, the type of x must be Number. If the specified x-axis is a category axis, the value of x must be one of the categorys, otherwise no line will be drawn.
+ x: Var[Union[str, int]]
+
+ # If set a string or a number, a horizontal line perpendicular to the y-axis specified by yAxisId will be drawn. If the specified y-axis is a number axis, the type of y must be Number. If the specified y-axis is a category axis, the value of y must be one of the categorys, otherwise no line will be drawn.
+ y: Var[Union[str, int]]
+
+ # The color of the reference line.
+ stroke: Var[Union[str, Color]]
+
+ # The width of the stroke. Default: 1
+ stroke_width: Var[Union[str, int]]
# Valid children components
_valid_children: List[str] = ["Label"]
+ # Array of endpoints in { x, y } format. These endpoints would be used to draw the ReferenceLine.
+ segment: List[Any] = []
+
class ReferenceDot(Reference):
"""A ReferenceDot component in Recharts."""
@@ -437,23 +696,47 @@ class ReferenceDot(Reference):
alias = "RechartsReferenceDot"
+ # If set a string or a number, a vertical line perpendicular to the x-axis specified by xAxisId will be drawn. If the specified x-axis is a number axis, the type of x must be Number. If the specified x-axis is a category axis, the value of x must be one of the categorys, otherwise no line will be drawn.
+ x: Var[Union[str, int]]
+
+ # If set a string or a number, a horizontal line perpendicular to the y-axis specified by yAxisId will be drawn. If the specified y-axis is a number axis, the type of y must be Number. If the specified y-axis is a category axis, the value of y must be one of the categorys, otherwise no line will be drawn.
+ y: Var[Union[str, int]]
+
+ # The radius of dot.
+ r: Var[int]
+
+ # The color of the area fill.
+ fill: Var[Union[str, Color]]
+
+ # The color of the line stroke.
+ stroke: Var[Union[str, Color]]
+
# Valid children components
_valid_children: List[str] = ["Label"]
- def get_event_triggers(self) -> dict[str, Union[Var, Any]]:
- """Get the event triggers that pass the component's value to the handler.
+ # The customized event handler of click on the component in this chart
+ on_click: EventHandler[empty_event]
- Returns:
- A dict mapping the event trigger to the var that is passed to the handler.
- """
- return {
- EventTriggers.ON_CLICK: lambda: [],
- EventTriggers.ON_MOUSE_MOVE: lambda: [],
- EventTriggers.ON_MOUSE_OVER: lambda: [],
- EventTriggers.ON_MOUSE_OUT: lambda: [],
- EventTriggers.ON_MOUSE_ENTER: lambda: [],
- EventTriggers.ON_MOUSE_LEAVE: lambda: [],
- }
+ # The customized event handler of mousedown on the component in this chart
+ on_mouse_down: EventHandler[empty_event]
+
+ # The customized event handler of mouseup on the component in this chart
+ on_mouse_up: EventHandler[empty_event]
+
+ # The customized event handler of mouseover on the component in this chart
+ on_mouse_over: EventHandler[empty_event]
+
+ # The customized event handler of mouseout on the component in this chart
+ on_mouse_out: EventHandler[empty_event]
+
+ # The customized event handler of mouseenter on the component in this chart
+ on_mouse_enter: EventHandler[empty_event]
+
+ # The customized event handler of mousemove on the component in this chart
+ on_mouse_move: EventHandler[empty_event]
+
+ # The customized event handler of mouseleave on the component in this chart
+ on_mouse_leave: EventHandler[empty_event]
class ReferenceArea(Recharts):
@@ -464,10 +747,10 @@ class ReferenceArea(Recharts):
alias = "RechartsReferenceArea"
# Stroke color
- stroke: Var[str]
+ stroke: Var[Union[str, Color]]
# Fill color
- fill: Var[str]
+ fill: Var[Union[str, Color]]
# The opacity of area.
fill_opacity: Var[float]
@@ -490,10 +773,10 @@ class ReferenceArea(Recharts):
# A boundary value of the area. If the specified y-axis is a number axis, the type of y must be Number. If the specified y-axis is a category axis, the value of y must be one of the categorys. If one of y1 or y2 is invalidate, the area will cover along y-axis.
y2: Var[Union[str, int]]
- # Defines how to draw the reference line if it falls partly outside the canvas. If set to 'discard', the reference line will not be drawn at all. If set to 'hidden', the reference line will be clipped to the canvas. If set to 'visible', the reference line will be drawn completely. If set to 'extendDomain', the domain of the overflown axis will be extended such that the reference line fits into the canvas.
+ # Defines how to draw the reference line if it falls partly outside the canvas. If set to 'discard', the reference line will not be drawn at all. If set to 'hidden', the reference line will be clipped to the canvas. If set to 'visible', the reference line will be drawn completely. If set to 'extendDomain', the domain of the overflown axis will be extended such that the reference line fits into the canvas. Default: "discard"
if_overflow: Var[LiteralIfOverflow]
- # If set true, the line will be rendered in front of bars in BarChart, etc.
+ # If set true, the line will be rendered in front of bars in BarChart, etc. Default: False
is_front: Var[bool]
# Valid children components
@@ -503,16 +786,16 @@ class ReferenceArea(Recharts):
class Grid(Recharts):
"""A base class for grid components in Recharts."""
- # The x-coordinate of grid.
+ # The x-coordinate of grid. Default: 0
x: Var[int]
- # The y-coordinate of grid.
+ # The y-coordinate of grid. Default: 0
y: Var[int]
- # The width of grid.
+ # The width of grid. Default: 0
width: Var[int]
- # The height of grid.
+ # The height of grid. Default: 0
height: Var[int]
@@ -523,21 +806,30 @@ class CartesianGrid(Grid):
alias = "RechartsCartesianGrid"
- # The horizontal line configuration.
- horizontal: Var[Dict[str, Any]]
+ # The horizontal line configuration. Default: True
+ horizontal: Var[bool]
- # The vertical line configuration.
- vertical: Var[Dict[str, Any]]
+ # The vertical line configuration. Default: True
+ vertical: Var[bool]
+
+ # The x-coordinates in pixel values of all vertical lines. Default: []
+ vertical_points: Var[List[Union[str, int]]]
+
+ # The x-coordinates in pixel values of all vertical lines. Default: []
+ horizontal_points: Var[List[Union[str, int]]]
# The background of grid.
- fill: Var[str]
+ fill: Var[Union[str, Color]]
- # The opacity of the background used to fill the space between grid lines
+ # The opacity of the background used to fill the space between grid lines.
fill_opacity: Var[float]
- # The pattern of dashes and gaps used to paint the lines of the grid
+ # The pattern of dashes and gaps used to paint the lines of the grid.
stroke_dasharray: Var[str]
+ # the stroke color of grid. Default: rx.color("gray", 7)
+ stroke: Var[Union[str, Color]] = LiteralVar.create(Color("gray", 7))
+
class CartesianAxis(Grid):
"""A CartesianAxis component in Recharts."""
@@ -546,29 +838,49 @@ class CartesianAxis(Grid):
alias = "RechartsCartesianAxis"
- # The orientation of axis 'top' | 'bottom' | 'left' | 'right'
+ # The orientation of axis 'top' | 'bottom' | 'left' | 'right'. Default: "bottom"
orientation: Var[LiteralOrientationTopBottomLeftRight]
- # If set false, no axis line will be drawn. If set a object, the option is the configuration of axis line.
+ # The box of viewing area. Default: {"x": 0, "y": 0, "width": 0, "height": 0}
+ view_box: Var[Dict[str, Any]]
+
+ # If set false, no axis line will be drawn. If set a object, the option is the configuration of axis line. Default: True
axis_line: Var[bool]
- # If set false, no axis tick lines will be drawn. If set a object, the option is the configuration of tick lines.
+ # If set false, no ticks will be drawn.
+ tick: Var[bool]
+
+ # If set false, no axis tick lines will be drawn. If set a object, the option is the configuration of tick lines. Default: True
tick_line: Var[bool]
- # The length of tick line.
+ # The length of tick line. Default: 6
tick_size: Var[int]
- # If set 0, all the ticks will be shown. If set preserveStart", "preserveEnd" or "preserveStartEnd", the ticks which is to be shown or hidden will be calculated automatically.
+ # If set 0, all the ticks will be shown. If set preserveStart", "preserveEnd" or "preserveStartEnd", the ticks which is to be shown or hidden will be calculated automatically. Default: "preserveEnd"
interval: Var[LiteralInterval]
- # If set false, no ticks will be drawn.
- ticks: Var[bool]
-
# If set a string or a number, default label will be drawn, and the option is content.
- label: Var[str]
+ label: Var[Union[str, int]]
- # If set true, flips ticks around the axis line, displaying the labels inside the chart instead of outside.
+ # If set true, flips ticks around the axis line, displaying the labels inside the chart instead of outside. Default: False
mirror: Var[bool]
# The margin between tick line and tick.
tick_margin: Var[int]
+
+
+area = Area.create
+bar = Bar.create
+line = Line.create
+scatter = Scatter.create
+x_axis = XAxis.create
+y_axis = YAxis.create
+z_axis = ZAxis.create
+brush = Brush.create
+cartesian_axis = CartesianAxis.create
+cartesian_grid = CartesianGrid.create
+reference_line = ReferenceLine.create
+reference_dot = ReferenceDot.create
+reference_area = ReferenceArea.create
+error_bar = ErrorBar.create
+funnel = Funnel.create
diff --git a/reflex/components/recharts/cartesian.pyi b/reflex/components/recharts/cartesian.pyi
index a12994d9e..983de30e3 100644
--- a/reflex/components/recharts/cartesian.pyi
+++ b/reflex/components/recharts/cartesian.pyi
@@ -1,139 +1,180 @@
"""Stub file for reflex/components/recharts/cartesian.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, List, Literal, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+from reflex.constants.colors import Color
+from reflex.event import EventType
from reflex.style import Style
-from typing import Any, Dict, List, Union
-from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.vars.base import Var
+
from .recharts import (
- LiteralAnimationEasing,
- LiteralAreaType,
- LiteralDirection,
- LiteralIfOverflow,
- LiteralInterval,
- LiteralLayout,
- LiteralLineType,
- LiteralOrientationTopBottom,
- LiteralOrientationTopBottomLeftRight,
- LiteralPolarRadiusType,
- LiteralScale,
- LiteralShape,
Recharts,
)
class Axis(Recharts):
- def get_event_triggers(self) -> dict[str, Union[Var, Any]]: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- data_key: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
+ data_key: Optional[Union[Var[Union[int, str]], int, str]] = None,
hide: Optional[Union[Var[bool], bool]] = None,
- orientation: Optional[
- Union[Var[Literal["top", "bottom"]], Literal["top", "bottom"]]
- ] = None,
+ width: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ height: Optional[Union[Var[Union[int, str]], int, str]] = None,
type_: Optional[
- Union[Var[Literal["number", "category"]], Literal["number", "category"]]
+ Union[Literal["category", "number"], Var[Literal["category", "number"]]]
+ ] = None,
+ interval: Optional[
+ Union[
+ Literal[
+ "equidistantPreserveStart",
+ "preserveEnd",
+ "preserveStart",
+ "preserveStartEnd",
+ ],
+ Var[
+ Union[
+ Literal[
+ "equidistantPreserveStart",
+ "preserveEnd",
+ "preserveStart",
+ "preserveStartEnd",
+ ],
+ int,
+ ]
+ ],
+ int,
+ ]
] = None,
allow_decimals: Optional[Union[Var[bool], bool]] = None,
allow_data_overflow: Optional[Union[Var[bool], bool]] = None,
allow_duplicated_category: Optional[Union[Var[bool], bool]] = None,
+ domain: Optional[Union[List, Var[List]]] = None,
axis_line: Optional[Union[Var[bool], bool]] = None,
- tick_line: Optional[Union[Var[bool], bool]] = None,
mirror: Optional[Union[Var[bool], bool]] = None,
reversed: Optional[Union[Var[bool], bool]] = None,
+ label: Optional[
+ Union[Dict[str, Any], Var[Union[Dict[str, Any], int, str]], int, str]
+ ] = None,
scale: Optional[
Union[
+ Literal[
+ "auto",
+ "band",
+ "identity",
+ "linear",
+ "log",
+ "ordinal",
+ "point",
+ "pow",
+ "quantile",
+ "quantize",
+ "sequential",
+ "sqrt",
+ "threshold",
+ "time",
+ "utc",
+ ],
Var[
Literal[
"auto",
- "linear",
- "pow",
- "sqrt",
- "log",
- "identity",
- "time",
"band",
- "point",
+ "identity",
+ "linear",
+ "log",
"ordinal",
+ "point",
+ "pow",
"quantile",
"quantize",
- "utc",
"sequential",
+ "sqrt",
"threshold",
+ "time",
+ "utc",
]
],
- Literal[
- "auto",
- "linear",
- "pow",
- "sqrt",
- "log",
- "identity",
- "time",
- "band",
- "point",
- "ordinal",
- "quantile",
- "quantize",
- "utc",
- "sequential",
- "threshold",
- ],
]
] = None,
- unit: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- name: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
+ unit: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ name: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ ticks: Optional[
+ Union[List[Union[int, str]], Var[List[Union[int, str]]]]
+ ] = None,
+ tick: Optional[Union[Var[bool], bool]] = None,
+ tick_count: Optional[Union[Var[int], int]] = None,
+ tick_line: Optional[Union[Var[bool], bool]] = None,
+ tick_size: Optional[Union[Var[int], int]] = None,
+ min_tick_gap: Optional[Union[Var[int], int]] = None,
+ stroke: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
+ text_anchor: Optional[
+ Union[
+ Literal["end", "middle", "start"],
+ Var[Literal["end", "middle", "start"]],
+ ]
+ ] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Axis":
"""Create the component.
Args:
*children: The children of the component.
- data_key: The key of a group of data which should be unique in an area chart.
- hide: If set true, the axis do not display in the chart.
- orientation: The orientation of axis 'top' | 'bottom'
+ data_key: The key of data displayed in the axis.
+ hide: If set true, the axis do not display in the chart. Default: False
+ width: The width of axis which is usually calculated internally.
+ height: The height of axis, which can be setted by user.
type_: The type of axis 'number' | 'category'
- allow_decimals: Allow the ticks of XAxis to be decimals or not.
- allow_data_overflow: When domain of the axis is specified and the type of the axis is 'number', if allowDataOverflow is set to be false, the domain will be adjusted when the minimum value of data is smaller than domain[0] or the maximum value of data is greater than domain[1] so that the axis displays all data values. If set to true, graphic elements (line, area, bars) will be clipped to conform to the specified domain.
- allow_duplicated_category: Allow the axis has duplicated categorys or not when the type of axis is "category".
- axis_line: If set false, no axis line will be drawn. If set a object, the option is the configuration of axis line.
- tick_line: If set false, no axis tick lines will be drawn. If set a object, the option is the configuration of tick lines.
- mirror: If set true, flips ticks around the axis line, displaying the labels inside the chart instead of outside.
- reversed: Reverse the ticks or not.
- scale: If 'auto' set, the scale function is decided by the type of chart, and the props type. 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utc' | 'sequential' | 'threshold' | Function
+ interval: If set 0, all the ticks will be shown. If set preserveStart", "preserveEnd" or "preserveStartEnd", the ticks which is to be shown or hidden will be calculated automatically. Default: "preserveEnd"
+ allow_decimals: Allow the ticks of Axis to be decimals or not. Default: True
+ allow_data_overflow: When domain of the axis is specified and the type of the axis is 'number', if allowDataOverflow is set to be false, the domain will be adjusted when the minimum value of data is smaller than domain[0] or the maximum value of data is greater than domain[1] so that the axis displays all data values. If set to true, graphic elements (line, area, bars) will be clipped to conform to the specified domain. Default: False
+ allow_duplicated_category: Allow the axis has duplicated categorys or not when the type of axis is "category". Default: True
+ domain: The range of the axis. Work best in conjuction with allow_data_overflow. Default: [0, "auto"]
+ axis_line: If set false, no axis line will be drawn. Default: True
+ mirror: If set true, flips ticks around the axis line, displaying the labels inside the chart instead of outside. Default: False
+ reversed: Reverse the ticks or not. Default: False
+ label: The label of axis, which appears next to the axis.
+ scale: If 'auto' set, the scale function is decided by the type of chart, and the props type. 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utc' | 'sequential' | 'threshold'. Default: "auto"
unit: The unit of data displayed in the axis. This option will be used to represent an index unit in a scatter chart.
name: The name of data displayed in the axis. This option will be used to represent an index in a scatter chart.
+ ticks: Set the values of axis ticks manually.
+ tick: If set false, no ticks will be drawn.
+ tick_count: The count of axis ticks. Not used if 'type' is 'category'. Default: 5
+ tick_line: If set false, no axis tick lines will be drawn. Default: True
+ tick_size: The length of tick line. Default: 6
+ min_tick_gap: The minimum gap between two adjacent labels. Default: 5
+ stroke: The stroke color of axis. Default: rx.color("gray", 9)
+ text_anchor: The text anchor of axis. Default: "middle"
+ on_click: The customized event handler of click on the ticks of this axis
+ on_mouse_down: The customized event handler of mousedown on the ticks of this axis
+ on_mouse_up: The customized event handler of mouseup on the ticks of this axis
+ on_mouse_move: The customized event handler of mousemove on the ticks of this axis
+ on_mouse_out: The customized event handler of mouseout on the ticks of this axis
+ on_mouse_enter: The customized event handler of mouseenter on the ticks of this axis
+ on_mouse_leave: The customized event handler of mouseleave on the ticks of this axis
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -153,107 +194,173 @@ class XAxis(Axis):
def create( # type: ignore
cls,
*children,
- data_key: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- hide: Optional[Union[Var[bool], bool]] = None,
orientation: Optional[
- Union[Var[Literal["top", "bottom"]], Literal["top", "bottom"]]
+ Union[Literal["bottom", "top"], Var[Literal["bottom", "top"]]]
] = None,
+ x_axis_id: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ include_hidden: Optional[Union[Var[bool], bool]] = None,
+ angle: Optional[Union[Var[int], int]] = None,
+ padding: Optional[Union[Dict[str, int], Var[Dict[str, int]]]] = None,
+ data_key: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ hide: Optional[Union[Var[bool], bool]] = None,
+ width: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ height: Optional[Union[Var[Union[int, str]], int, str]] = None,
type_: Optional[
- Union[Var[Literal["number", "category"]], Literal["number", "category"]]
+ Union[Literal["category", "number"], Var[Literal["category", "number"]]]
+ ] = None,
+ interval: Optional[
+ Union[
+ Literal[
+ "equidistantPreserveStart",
+ "preserveEnd",
+ "preserveStart",
+ "preserveStartEnd",
+ ],
+ Var[
+ Union[
+ Literal[
+ "equidistantPreserveStart",
+ "preserveEnd",
+ "preserveStart",
+ "preserveStartEnd",
+ ],
+ int,
+ ]
+ ],
+ int,
+ ]
] = None,
allow_decimals: Optional[Union[Var[bool], bool]] = None,
allow_data_overflow: Optional[Union[Var[bool], bool]] = None,
allow_duplicated_category: Optional[Union[Var[bool], bool]] = None,
+ domain: Optional[Union[List, Var[List]]] = None,
axis_line: Optional[Union[Var[bool], bool]] = None,
- tick_line: Optional[Union[Var[bool], bool]] = None,
mirror: Optional[Union[Var[bool], bool]] = None,
reversed: Optional[Union[Var[bool], bool]] = None,
+ label: Optional[
+ Union[Dict[str, Any], Var[Union[Dict[str, Any], int, str]], int, str]
+ ] = None,
scale: Optional[
Union[
+ Literal[
+ "auto",
+ "band",
+ "identity",
+ "linear",
+ "log",
+ "ordinal",
+ "point",
+ "pow",
+ "quantile",
+ "quantize",
+ "sequential",
+ "sqrt",
+ "threshold",
+ "time",
+ "utc",
+ ],
Var[
Literal[
"auto",
- "linear",
- "pow",
- "sqrt",
- "log",
- "identity",
- "time",
"band",
- "point",
+ "identity",
+ "linear",
+ "log",
"ordinal",
+ "point",
+ "pow",
"quantile",
"quantize",
- "utc",
"sequential",
+ "sqrt",
"threshold",
+ "time",
+ "utc",
]
],
- Literal[
- "auto",
- "linear",
- "pow",
- "sqrt",
- "log",
- "identity",
- "time",
- "band",
- "point",
- "ordinal",
- "quantile",
- "quantize",
- "utc",
- "sequential",
- "threshold",
- ],
]
] = None,
- unit: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- name: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
+ unit: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ name: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ ticks: Optional[
+ Union[List[Union[int, str]], Var[List[Union[int, str]]]]
+ ] = None,
+ tick: Optional[Union[Var[bool], bool]] = None,
+ tick_count: Optional[Union[Var[int], int]] = None,
+ tick_line: Optional[Union[Var[bool], bool]] = None,
+ tick_size: Optional[Union[Var[int], int]] = None,
+ min_tick_gap: Optional[Union[Var[int], int]] = None,
+ stroke: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
+ text_anchor: Optional[
+ Union[
+ Literal["end", "middle", "start"],
+ Var[Literal["end", "middle", "start"]],
+ ]
+ ] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "XAxis":
"""Create the component.
Args:
*children: The children of the component.
- data_key: The key of a group of data which should be unique in an area chart.
- hide: If set true, the axis do not display in the chart.
- orientation: The orientation of axis 'top' | 'bottom'
+ orientation: The orientation of axis 'top' | 'bottom'. Default: "bottom"
+ x_axis_id: The id of x-axis which is corresponding to the data. Default: 0
+ include_hidden: Ensures that all datapoints within a chart contribute to its domain calculation, even when they are hidden. Default: False
+ angle: The angle of axis ticks. Default: 0
+ padding: Specify the padding of x-axis. Default: {"left": 0, "right": 0}
+ data_key: The key of data displayed in the axis.
+ hide: If set true, the axis do not display in the chart. Default: False
+ width: The width of axis which is usually calculated internally.
+ height: The height of axis, which can be setted by user.
type_: The type of axis 'number' | 'category'
- allow_decimals: Allow the ticks of XAxis to be decimals or not.
- allow_data_overflow: When domain of the axis is specified and the type of the axis is 'number', if allowDataOverflow is set to be false, the domain will be adjusted when the minimum value of data is smaller than domain[0] or the maximum value of data is greater than domain[1] so that the axis displays all data values. If set to true, graphic elements (line, area, bars) will be clipped to conform to the specified domain.
- allow_duplicated_category: Allow the axis has duplicated categorys or not when the type of axis is "category".
- axis_line: If set false, no axis line will be drawn. If set a object, the option is the configuration of axis line.
- tick_line: If set false, no axis tick lines will be drawn. If set a object, the option is the configuration of tick lines.
- mirror: If set true, flips ticks around the axis line, displaying the labels inside the chart instead of outside.
- reversed: Reverse the ticks or not.
- scale: If 'auto' set, the scale function is decided by the type of chart, and the props type. 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utc' | 'sequential' | 'threshold' | Function
+ interval: If set 0, all the ticks will be shown. If set preserveStart", "preserveEnd" or "preserveStartEnd", the ticks which is to be shown or hidden will be calculated automatically. Default: "preserveEnd"
+ allow_decimals: Allow the ticks of Axis to be decimals or not. Default: True
+ allow_data_overflow: When domain of the axis is specified and the type of the axis is 'number', if allowDataOverflow is set to be false, the domain will be adjusted when the minimum value of data is smaller than domain[0] or the maximum value of data is greater than domain[1] so that the axis displays all data values. If set to true, graphic elements (line, area, bars) will be clipped to conform to the specified domain. Default: False
+ allow_duplicated_category: Allow the axis has duplicated categorys or not when the type of axis is "category". Default: True
+ domain: The range of the axis. Work best in conjuction with allow_data_overflow. Default: [0, "auto"]
+ axis_line: If set false, no axis line will be drawn. Default: True
+ mirror: If set true, flips ticks around the axis line, displaying the labels inside the chart instead of outside. Default: False
+ reversed: Reverse the ticks or not. Default: False
+ label: The label of axis, which appears next to the axis.
+ scale: If 'auto' set, the scale function is decided by the type of chart, and the props type. 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utc' | 'sequential' | 'threshold'. Default: "auto"
unit: The unit of data displayed in the axis. This option will be used to represent an index unit in a scatter chart.
name: The name of data displayed in the axis. This option will be used to represent an index in a scatter chart.
+ ticks: Set the values of axis ticks manually.
+ tick: If set false, no ticks will be drawn.
+ tick_count: The count of axis ticks. Not used if 'type' is 'category'. Default: 5
+ tick_line: If set false, no axis tick lines will be drawn. Default: True
+ tick_size: The length of tick line. Default: 6
+ min_tick_gap: The minimum gap between two adjacent labels. Default: 5
+ stroke: The stroke color of axis. Default: rx.color("gray", 9)
+ text_anchor: The text anchor of axis. Default: "middle"
+ on_click: The customized event handler of click on the ticks of this axis
+ on_mouse_down: The customized event handler of mousedown on the ticks of this axis
+ on_mouse_up: The customized event handler of mouseup on the ticks of this axis
+ on_mouse_move: The customized event handler of mousemove on the ticks of this axis
+ on_mouse_out: The customized event handler of mouseout on the ticks of this axis
+ on_mouse_enter: The customized event handler of mouseenter on the ticks of this axis
+ on_mouse_leave: The customized event handler of mouseleave on the ticks of this axis
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -273,107 +380,169 @@ class YAxis(Axis):
def create( # type: ignore
cls,
*children,
- data_key: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- hide: Optional[Union[Var[bool], bool]] = None,
orientation: Optional[
- Union[Var[Literal["top", "bottom"]], Literal["top", "bottom"]]
+ Union[Literal["left", "right"], Var[Literal["left", "right"]]]
] = None,
+ y_axis_id: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ padding: Optional[Union[Dict[str, int], Var[Dict[str, int]]]] = None,
+ data_key: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ hide: Optional[Union[Var[bool], bool]] = None,
+ width: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ height: Optional[Union[Var[Union[int, str]], int, str]] = None,
type_: Optional[
- Union[Var[Literal["number", "category"]], Literal["number", "category"]]
+ Union[Literal["category", "number"], Var[Literal["category", "number"]]]
+ ] = None,
+ interval: Optional[
+ Union[
+ Literal[
+ "equidistantPreserveStart",
+ "preserveEnd",
+ "preserveStart",
+ "preserveStartEnd",
+ ],
+ Var[
+ Union[
+ Literal[
+ "equidistantPreserveStart",
+ "preserveEnd",
+ "preserveStart",
+ "preserveStartEnd",
+ ],
+ int,
+ ]
+ ],
+ int,
+ ]
] = None,
allow_decimals: Optional[Union[Var[bool], bool]] = None,
allow_data_overflow: Optional[Union[Var[bool], bool]] = None,
allow_duplicated_category: Optional[Union[Var[bool], bool]] = None,
+ domain: Optional[Union[List, Var[List]]] = None,
axis_line: Optional[Union[Var[bool], bool]] = None,
- tick_line: Optional[Union[Var[bool], bool]] = None,
mirror: Optional[Union[Var[bool], bool]] = None,
reversed: Optional[Union[Var[bool], bool]] = None,
+ label: Optional[
+ Union[Dict[str, Any], Var[Union[Dict[str, Any], int, str]], int, str]
+ ] = None,
scale: Optional[
Union[
+ Literal[
+ "auto",
+ "band",
+ "identity",
+ "linear",
+ "log",
+ "ordinal",
+ "point",
+ "pow",
+ "quantile",
+ "quantize",
+ "sequential",
+ "sqrt",
+ "threshold",
+ "time",
+ "utc",
+ ],
Var[
Literal[
"auto",
- "linear",
- "pow",
- "sqrt",
- "log",
- "identity",
- "time",
"band",
- "point",
+ "identity",
+ "linear",
+ "log",
"ordinal",
+ "point",
+ "pow",
"quantile",
"quantize",
- "utc",
"sequential",
+ "sqrt",
"threshold",
+ "time",
+ "utc",
]
],
- Literal[
- "auto",
- "linear",
- "pow",
- "sqrt",
- "log",
- "identity",
- "time",
- "band",
- "point",
- "ordinal",
- "quantile",
- "quantize",
- "utc",
- "sequential",
- "threshold",
- ],
]
] = None,
- unit: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- name: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
+ unit: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ name: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ ticks: Optional[
+ Union[List[Union[int, str]], Var[List[Union[int, str]]]]
+ ] = None,
+ tick: Optional[Union[Var[bool], bool]] = None,
+ tick_count: Optional[Union[Var[int], int]] = None,
+ tick_line: Optional[Union[Var[bool], bool]] = None,
+ tick_size: Optional[Union[Var[int], int]] = None,
+ min_tick_gap: Optional[Union[Var[int], int]] = None,
+ stroke: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
+ text_anchor: Optional[
+ Union[
+ Literal["end", "middle", "start"],
+ Var[Literal["end", "middle", "start"]],
+ ]
+ ] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "YAxis":
"""Create the component.
Args:
*children: The children of the component.
- data_key: The key of a group of data which should be unique in an area chart.
- hide: If set true, the axis do not display in the chart.
- orientation: The orientation of axis 'top' | 'bottom'
+ orientation: The orientation of axis 'left' | 'right'. Default: "left"
+ y_axis_id: The id of y-axis which is corresponding to the data. Default: 0
+ padding: Specify the padding of y-axis. Default: {"top": 0, "bottom": 0}
+ data_key: The key of data displayed in the axis.
+ hide: If set true, the axis do not display in the chart. Default: False
+ width: The width of axis which is usually calculated internally.
+ height: The height of axis, which can be setted by user.
type_: The type of axis 'number' | 'category'
- allow_decimals: Allow the ticks of XAxis to be decimals or not.
- allow_data_overflow: When domain of the axis is specified and the type of the axis is 'number', if allowDataOverflow is set to be false, the domain will be adjusted when the minimum value of data is smaller than domain[0] or the maximum value of data is greater than domain[1] so that the axis displays all data values. If set to true, graphic elements (line, area, bars) will be clipped to conform to the specified domain.
- allow_duplicated_category: Allow the axis has duplicated categorys or not when the type of axis is "category".
- axis_line: If set false, no axis line will be drawn. If set a object, the option is the configuration of axis line.
- tick_line: If set false, no axis tick lines will be drawn. If set a object, the option is the configuration of tick lines.
- mirror: If set true, flips ticks around the axis line, displaying the labels inside the chart instead of outside.
- reversed: Reverse the ticks or not.
- scale: If 'auto' set, the scale function is decided by the type of chart, and the props type. 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utc' | 'sequential' | 'threshold' | Function
+ interval: If set 0, all the ticks will be shown. If set preserveStart", "preserveEnd" or "preserveStartEnd", the ticks which is to be shown or hidden will be calculated automatically. Default: "preserveEnd"
+ allow_decimals: Allow the ticks of Axis to be decimals or not. Default: True
+ allow_data_overflow: When domain of the axis is specified and the type of the axis is 'number', if allowDataOverflow is set to be false, the domain will be adjusted when the minimum value of data is smaller than domain[0] or the maximum value of data is greater than domain[1] so that the axis displays all data values. If set to true, graphic elements (line, area, bars) will be clipped to conform to the specified domain. Default: False
+ allow_duplicated_category: Allow the axis has duplicated categorys or not when the type of axis is "category". Default: True
+ domain: The range of the axis. Work best in conjuction with allow_data_overflow. Default: [0, "auto"]
+ axis_line: If set false, no axis line will be drawn. Default: True
+ mirror: If set true, flips ticks around the axis line, displaying the labels inside the chart instead of outside. Default: False
+ reversed: Reverse the ticks or not. Default: False
+ label: The label of axis, which appears next to the axis.
+ scale: If 'auto' set, the scale function is decided by the type of chart, and the props type. 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utc' | 'sequential' | 'threshold'. Default: "auto"
unit: The unit of data displayed in the axis. This option will be used to represent an index unit in a scatter chart.
name: The name of data displayed in the axis. This option will be used to represent an index in a scatter chart.
+ ticks: Set the values of axis ticks manually.
+ tick: If set false, no ticks will be drawn.
+ tick_count: The count of axis ticks. Not used if 'type' is 'category'. Default: 5
+ tick_line: If set false, no axis tick lines will be drawn. Default: True
+ tick_size: The length of tick line. Default: 6
+ min_tick_gap: The minimum gap between two adjacent labels. Default: 5
+ stroke: The stroke color of axis. Default: rx.color("gray", 9)
+ text_anchor: The text anchor of axis. Default: "middle"
+ on_click: The customized event handler of click on the ticks of this axis
+ on_mouse_down: The customized event handler of mousedown on the ticks of this axis
+ on_mouse_up: The customized event handler of mouseup on the ticks of this axis
+ on_mouse_move: The customized event handler of mousemove on the ticks of this axis
+ on_mouse_out: The customized event handler of mouseout on the ticks of this axis
+ on_mouse_enter: The customized event handler of mouseenter on the ticks of this axis
+ on_mouse_leave: The customized event handler of mouseleave on the ticks of this axis
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -393,48 +562,49 @@ class ZAxis(Recharts):
def create( # type: ignore
cls,
*children,
- data_key: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- range: Optional[Union[Var[List[int]], List[int]]] = None,
- unit: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- name: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
+ data_key: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ z_axis_id: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ range: Optional[Union[List[int], Var[List[int]]]] = None,
+ unit: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ name: Optional[Union[Var[Union[int, str]], int, str]] = None,
scale: Optional[
Union[
+ Literal[
+ "auto",
+ "band",
+ "identity",
+ "linear",
+ "log",
+ "ordinal",
+ "point",
+ "pow",
+ "quantile",
+ "quantize",
+ "sequential",
+ "sqrt",
+ "threshold",
+ "time",
+ "utc",
+ ],
Var[
Literal[
"auto",
- "linear",
- "pow",
- "sqrt",
- "log",
- "identity",
- "time",
"band",
- "point",
+ "identity",
+ "linear",
+ "log",
"ordinal",
+ "point",
+ "pow",
"quantile",
"quantize",
- "utc",
"sequential",
+ "sqrt",
"threshold",
+ "time",
+ "utc",
]
],
- Literal[
- "auto",
- "linear",
- "pow",
- "sqrt",
- "log",
- "identity",
- "time",
- "band",
- "point",
- "ordinal",
- "quantile",
- "quantize",
- "utc",
- "sequential",
- "threshold",
- ],
]
] = None,
style: Optional[Style] = None,
@@ -443,62 +613,33 @@ class ZAxis(Recharts):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ZAxis":
"""Create the component.
Args:
*children: The children of the component.
data_key: The key of data displayed in the axis.
- range: The range of axis.
+ z_axis_id: The unique id of z-axis. Default: 0
+ range: The range of axis. Default: [10, 10]
unit: The unit of data displayed in the axis. This option will be used to represent an index unit in a scatter chart.
name: The name of data displayed in the axis. This option will be used to represent an index in a scatter chart.
- scale: If 'auto' set, the scale function is decided by the type of chart, and the props type.
+ scale: If 'auto' set, the scale function is decided by the type of chart, and the props type. Default: "auto"
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -519,13 +660,14 @@ class Brush(Recharts):
def create( # type: ignore
cls,
*children,
- stroke: Optional[Union[Var[str], str]] = None,
- data_key: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
+ stroke: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
+ fill: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
+ data_key: Optional[Union[Var[Union[int, str]], int, str]] = None,
x: Optional[Union[Var[int], int]] = None,
y: Optional[Union[Var[int], int]] = None,
width: Optional[Union[Var[int], int]] = None,
height: Optional[Union[Var[int], int]] = None,
- data: Optional[Union[Var[List[Any]], List[Any]]] = None,
+ data: Optional[Union[List[Any], Var[List[Any]]]] = None,
traveller_width: Optional[Union[Var[int], int]] = None,
gap: Optional[Union[Var[int], int]] = None,
start_index: Optional[Union[Var[int], int]] = None,
@@ -536,26 +678,25 @@ class Brush(Recharts):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_change: Optional[EventType[[]]] = None,
+ **props,
) -> "Brush":
"""Create the component.
Args:
*children: The children of the component.
- stroke: Stroke color
+ stroke: The stroke color of brush
+ fill: The fill color of brush
data_key: The key of data displayed in the axis.
- x: The x-coordinate of brush.
- y: The y-coordinate of brush.
- width: The width of brush.
- height: The height of brush.
- data: The data domain of brush, [min, max].
- traveller_width: The width of each traveller.
- gap: The data with gap of refreshing chart. If the option is not set, the chart will be refreshed every time
- start_index: The default start index of brush. If the option is not set, the start index will be 0.
- end_index: The default end index of brush. If the option is not set, the end index will be 1.
+ x: The x-coordinate of brush. Default: 0
+ y: The y-coordinate of brush. Default: 0
+ width: The width of brush. Default: 0
+ height: The height of brush. Default: 40
+ data: The original data of a LineChart, a BarChart or an AreaChart.
+ traveller_width: The width of each traveller. Default: 5
+ gap: The data with gap of refreshing chart. If the option is not set, the chart will be refreshed every time. Default: 1
+ start_index: The default start index of brush. If the option is not set, the start index will be 0. Default: 0
+ end_index: The default end index of brush. If the option is not set, the end index will be calculated by the length of data.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -570,7 +711,6 @@ class Brush(Recharts):
...
class Cartesian(Recharts):
- def get_event_triggers(self) -> dict[str, Union[Var, Any]]: ...
@overload
@classmethod
def create( # type: ignore
@@ -578,38 +718,80 @@ class Cartesian(Recharts):
*children,
layout: Optional[
Union[
- Var[Literal["horizontal", "vertical"]],
Literal["horizontal", "vertical"],
+ Var[Literal["horizontal", "vertical"]],
]
] = None,
- data_key: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- x_axis_id: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- y_axis_id: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
+ data_key: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ x_axis_id: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ y_axis_id: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ legend_type: Optional[
+ Union[
+ Literal[
+ "circle",
+ "cross",
+ "diamond",
+ "line",
+ "none",
+ "plainline",
+ "rect",
+ "square",
+ "star",
+ "triangle",
+ "wye",
+ ],
+ Var[
+ Literal[
+ "circle",
+ "cross",
+ "diamond",
+ "line",
+ "none",
+ "plainline",
+ "rect",
+ "square",
+ "star",
+ "triangle",
+ "wye",
+ ]
+ ],
+ ]
+ ] = None,
+ is_animation_active: Optional[Union[Var[bool], bool]] = None,
+ animation_begin: Optional[Union[Var[int], int]] = None,
+ animation_duration: Optional[Union[Var[int], int]] = None,
+ animation_easing: Optional[
+ Union[
+ Literal["ease", "ease-in", "ease-in-out", "ease-out", "linear"],
+ Var[Literal["ease", "ease-in", "ease-in-out", "ease-out", "linear"]],
+ ]
+ ] = None,
+ unit: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ name: Optional[Union[Var[Union[int, str]], int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_animation_end: Optional[EventType[[]]] = None,
+ on_animation_start: Optional[EventType[[]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Cartesian":
"""Create the component.
@@ -617,9 +799,26 @@ class Cartesian(Recharts):
*children: The children of the component.
layout: The layout of bar in the chart, usually inherited from parent. 'horizontal' | 'vertical'
data_key: The key of a group of data which should be unique in an area chart.
- x_axis_id: The id of x-axis which is corresponding to the data.
- y_axis_id: The id of y-axis which is corresponding to the data.
- style: The type of icon in legend. If set to 'none', no legend item will be rendered. 'line' | 'plainline' | 'square' | 'rect'| 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye' | 'none'optional legend_type: Var[LiteralLegendType] The style of the component.
+ x_axis_id: The id of x-axis which is corresponding to the data. Default: 0
+ y_axis_id: The id of y-axis which is corresponding to the data. Default: 0
+ legend_type: The type of icon in legend. If set to 'none', no legend item will be rendered. 'line' | 'plainline' | 'square' | 'rect'| 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye' | 'none' optional
+ is_animation_active: If set false, animation of bar will be disabled. Default: True
+ animation_begin: Specifies when the animation should begin, the unit of this option is ms. Default: 0
+ animation_duration: Specifies the duration of animation, the unit of this option is ms. Default: 1500
+ animation_easing: The type of easing function. Default: "ease"
+ unit: The unit of data. This option will be used in tooltip.
+ name: The name of data. This option will be used in tooltip and legend to represent the component. If no value was set to this option, the value of dataKey will be used alternatively.
+ on_animation_start: The customized event handler of animation start
+ on_animation_end: The customized event handler of animation end
+ on_click: The customized event handler of click on the component in this group
+ on_mouse_down: The customized event handler of mousedown on the component in this group
+ on_mouse_up: The customized event handler of mouseup on the component in this group
+ on_mouse_move: The customized event handler of mousemove on the component in this group
+ on_mouse_over: The customized event handler of mouseover on the component in this group
+ on_mouse_out: The customized event handler of mouseout on the component in this group
+ on_mouse_enter: The customized event handler of mouseenter on the component in this group
+ on_mouse_leave: The customized event handler of mouseleave on the component in this group
+ style: The style of the component.
key: A unique key for the component.
id: The id for the component.
class_name: The class name for the component.
@@ -638,105 +837,176 @@ class Area(Cartesian):
def create( # type: ignore
cls,
*children,
- stroke: Optional[Union[Var[str], str]] = None,
+ stroke: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
stroke_width: Optional[Union[Var[int], int]] = None,
- fill: Optional[Union[Var[str], str]] = None,
+ fill: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
type_: Optional[
Union[
+ Literal[
+ "basis",
+ "basisClosed",
+ "basisOpen",
+ "bump",
+ "bumpX",
+ "bumpY",
+ "linear",
+ "linearClosed",
+ "monotone",
+ "monotoneX",
+ "monotoneY",
+ "natural",
+ "step",
+ "stepAfter",
+ "stepBefore",
+ ],
Var[
Literal[
"basis",
"basisClosed",
"basisOpen",
+ "bump",
"bumpX",
"bumpY",
- "bump",
"linear",
"linearClosed",
- "natural",
+ "monotone",
"monotoneX",
"monotoneY",
- "monotone",
+ "natural",
"step",
- "stepBefore",
"stepAfter",
+ "stepBefore",
]
],
+ ]
+ ] = None,
+ dot: Optional[
+ Union[Dict[str, Any], Var[Union[Dict[str, Any], bool]], bool]
+ ] = None,
+ active_dot: Optional[
+ Union[Dict[str, Any], Var[Union[Dict[str, Any], bool]], bool]
+ ] = None,
+ label: Optional[Union[Var[bool], bool]] = None,
+ base_line: Optional[
+ Union[List[Dict[str, Any]], Var[Union[List[Dict[str, Any]], str]], str]
+ ] = None,
+ points: Optional[Union[List[Dict[str, Any]], Var[List[Dict[str, Any]]]]] = None,
+ stack_id: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ connect_nulls: Optional[Union[Var[bool], bool]] = None,
+ layout: Optional[
+ Union[
+ Literal["horizontal", "vertical"],
+ Var[Literal["horizontal", "vertical"]],
+ ]
+ ] = None,
+ data_key: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ x_axis_id: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ y_axis_id: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ legend_type: Optional[
+ Union[
Literal[
- "basis",
- "basisClosed",
- "basisOpen",
- "bumpX",
- "bumpY",
- "bump",
- "linear",
- "linearClosed",
- "natural",
- "monotoneX",
- "monotoneY",
- "monotone",
- "step",
- "stepBefore",
- "stepAfter",
+ "circle",
+ "cross",
+ "diamond",
+ "line",
+ "none",
+ "plainline",
+ "rect",
+ "square",
+ "star",
+ "triangle",
+ "wye",
+ ],
+ Var[
+ Literal[
+ "circle",
+ "cross",
+ "diamond",
+ "line",
+ "none",
+ "plainline",
+ "rect",
+ "square",
+ "star",
+ "triangle",
+ "wye",
+ ]
],
]
] = None,
- dot: Optional[Union[Var[bool], bool]] = None,
- active_dot: Optional[Union[Var[bool], bool]] = None,
- label: Optional[Union[Var[bool], bool]] = None,
- stack_id: Optional[Union[Var[str], str]] = None,
- layout: Optional[
+ is_animation_active: Optional[Union[Var[bool], bool]] = None,
+ animation_begin: Optional[Union[Var[int], int]] = None,
+ animation_duration: Optional[Union[Var[int], int]] = None,
+ animation_easing: Optional[
Union[
- Var[Literal["horizontal", "vertical"]],
- Literal["horizontal", "vertical"],
+ Literal["ease", "ease-in", "ease-in-out", "ease-out", "linear"],
+ Var[Literal["ease", "ease-in", "ease-in-out", "ease-out", "linear"]],
]
] = None,
- data_key: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- x_axis_id: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- y_axis_id: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
+ unit: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ name: Optional[Union[Var[Union[int, str]], int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_animation_end: Optional[EventType[[]]] = None,
+ on_animation_start: Optional[EventType[[]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Area":
"""Create the component.
Args:
*children: The children of the component.
- stroke: The color of the line stroke.
- stroke_width: The width of the line stroke.
- fill: The color of the area fill.
- type_: The interpolation type of area. And customized interpolation function can be set to type. 'basis' | 'basisClosed' | 'basisOpen' | 'bumpX' | 'bumpY' | 'bump' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' |
- dot: If false set, dots will not be drawn. If true set, dots will be drawn which have the props calculated internally.
- active_dot: The dot is shown when user enter an area chart and this chart has tooltip. If false set, no active dot will not be drawn. If true set, active dot will be drawn which have the props calculated internally.
- label: If false set, labels will not be drawn. If true set, labels will be drawn which have the props calculated internally.
- stack_id: The stack id of area, when two areas have the same value axis and same stackId, then the two areas area stacked in order.
+ stroke: The color of the line stroke. Default: rx.color("accent", 9)
+ stroke_width: The width of the line stroke. Default: 1
+ fill: The color of the area fill. Default: rx.color("accent", 5)
+ type_: The interpolation type of area. And customized interpolation function can be set to type. 'basis' | 'basisClosed' | 'basisOpen' | 'bumpX' | 'bumpY' | 'bump' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter'. Default: "monotone"
+ dot: If false set, dots will not be drawn. If true set, dots will be drawn which have the props calculated internally. Default: False
+ active_dot: The dot is shown when user enter an area chart and this chart has tooltip. If false set, no active dot will not be drawn. If true set, active dot will be drawn which have the props calculated internally. Default: {stroke: rx.color("accent", 2), fill: rx.color("accent", 10)}
+ label: If set false, labels will not be drawn. If set true, labels will be drawn which have the props calculated internally. Default: False
+ base_line: The value which can describle the line, usually calculated internally.
+ points: The coordinates of all the points in the area, usually calculated internally.
+ stack_id: The stack id of area, when two areas have the same value axis and same stack_id, then the two areas are stacked in order.
+ connect_nulls: Whether to connect a graph area across null points. Default: False
layout: The layout of bar in the chart, usually inherited from parent. 'horizontal' | 'vertical'
data_key: The key of a group of data which should be unique in an area chart.
- x_axis_id: The id of x-axis which is corresponding to the data.
- y_axis_id: The id of y-axis which is corresponding to the data.
- style: The type of icon in legend. If set to 'none', no legend item will be rendered. 'line' | 'plainline' | 'square' | 'rect'| 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye' | 'none'optional legend_type: Var[LiteralLegendType] The style of the component.
+ x_axis_id: The id of x-axis which is corresponding to the data. Default: 0
+ y_axis_id: The id of y-axis which is corresponding to the data. Default: 0
+ legend_type: The type of icon in legend. If set to 'none', no legend item will be rendered. 'line' | 'plainline' | 'square' | 'rect'| 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye' | 'none' optional
+ is_animation_active: If set false, animation of bar will be disabled. Default: True
+ animation_begin: Specifies when the animation should begin, the unit of this option is ms. Default: 0
+ animation_duration: Specifies the duration of animation, the unit of this option is ms. Default: 1500
+ animation_easing: The type of easing function. Default: "ease"
+ unit: The unit of data. This option will be used in tooltip.
+ name: The name of data. This option will be used in tooltip and legend to represent the component. If no value was set to this option, the value of dataKey will be used alternatively.
+ on_animation_start: The customized event handler of animation start
+ on_animation_end: The customized event handler of animation end
+ on_click: The customized event handler of click on the component in this group
+ on_mouse_down: The customized event handler of mousedown on the component in this group
+ on_mouse_up: The customized event handler of mouseup on the component in this group
+ on_mouse_move: The customized event handler of mousemove on the component in this group
+ on_mouse_over: The customized event handler of mouseover on the component in this group
+ on_mouse_out: The customized event handler of mouseout on the component in this group
+ on_mouse_enter: The customized event handler of mouseenter on the component in this group
+ on_mouse_leave: The customized event handler of mouseleave on the component in this group
+ style: The style of the component.
key: A unique key for the component.
id: The id for the component.
class_name: The class name for the component.
@@ -755,48 +1025,92 @@ class Bar(Cartesian):
def create( # type: ignore
cls,
*children,
- stroke: Optional[Union[Var[str], str]] = None,
+ stroke: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
stroke_width: Optional[Union[Var[int], int]] = None,
- fill: Optional[Union[Var[str], str]] = None,
+ fill: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
background: Optional[Union[Var[bool], bool]] = None,
label: Optional[Union[Var[bool], bool]] = None,
stack_id: Optional[Union[Var[str], str]] = None,
+ unit: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ min_point_size: Optional[Union[Var[int], int]] = None,
+ name: Optional[Union[Var[Union[int, str]], int, str]] = None,
bar_size: Optional[Union[Var[int], int]] = None,
max_bar_size: Optional[Union[Var[int], int]] = None,
+ radius: Optional[Union[List[int], Var[Union[List[int], int]], int]] = None,
layout: Optional[
Union[
- Var[Literal["horizontal", "vertical"]],
Literal["horizontal", "vertical"],
+ Var[Literal["horizontal", "vertical"]],
+ ]
+ ] = None,
+ data_key: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ x_axis_id: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ y_axis_id: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ legend_type: Optional[
+ Union[
+ Literal[
+ "circle",
+ "cross",
+ "diamond",
+ "line",
+ "none",
+ "plainline",
+ "rect",
+ "square",
+ "star",
+ "triangle",
+ "wye",
+ ],
+ Var[
+ Literal[
+ "circle",
+ "cross",
+ "diamond",
+ "line",
+ "none",
+ "plainline",
+ "rect",
+ "square",
+ "star",
+ "triangle",
+ "wye",
+ ]
+ ],
+ ]
+ ] = None,
+ is_animation_active: Optional[Union[Var[bool], bool]] = None,
+ animation_begin: Optional[Union[Var[int], int]] = None,
+ animation_duration: Optional[Union[Var[int], int]] = None,
+ animation_easing: Optional[
+ Union[
+ Literal["ease", "ease-in", "ease-in-out", "ease-out", "linear"],
+ Var[Literal["ease", "ease-in", "ease-in-out", "ease-out", "linear"]],
]
] = None,
- data_key: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- x_axis_id: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- y_axis_id: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_animation_end: Optional[EventType[[]]] = None,
+ on_animation_start: Optional[EventType[[]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Bar":
"""Create the component.
@@ -804,17 +1118,36 @@ class Bar(Cartesian):
*children: The children of the component.
stroke: The color of the line stroke.
stroke_width: The width of the line stroke.
- fill: The width of the line stroke.
- background: If false set, background of bars will not be drawn. If true set, background of bars will be drawn which have the props calculated internally.
- label: If false set, labels will not be drawn. If true set, labels will be drawn which have the props calculated internally.
- stack_id: The stack id of bar, when two areas have the same value axis and same stackId, then the two areas area stacked in order.
- bar_size: Size of the bar
+ fill: The width of the line stroke. Default: Color("accent", 9)
+ background: If false set, background of bars will not be drawn. If true set, background of bars will be drawn which have the props calculated internally. Default: False
+ label: If false set, labels will not be drawn. If true set, labels will be drawn which have the props calculated internally. Default: False
+ stack_id: The stack id of bar, when two bars have the same value axis and same stack_id, then the two bars are stacked in order.
+ unit: The unit of data. This option will be used in tooltip.
+ min_point_size: The minimal height of a bar in a horizontal BarChart, or the minimal width of a bar in a vertical BarChart. By default, 0 values are not shown. To visualize a 0 (or close to zero) point, set the minimal point size to a pixel value like 3. In stacked bar charts, minPointSize might not be respected for tightly packed values. So we strongly recommend not using this prop in stacked BarCharts.
+ name: The name of data. This option will be used in tooltip and legend to represent the component. If no value was set to this option, the value of dataKey will be used alternatively.
+ bar_size: Size of the bar (if one bar_size is set then a bar_size must be set for all bars)
max_bar_size: Max size of the bar
+ radius: If set a value, the option is the radius of all the rounded corners. If set a array, the option are in turn the radiuses of top-left corner, top-right corner, bottom-right corner, bottom-left corner. Default: 0
layout: The layout of bar in the chart, usually inherited from parent. 'horizontal' | 'vertical'
data_key: The key of a group of data which should be unique in an area chart.
- x_axis_id: The id of x-axis which is corresponding to the data.
- y_axis_id: The id of y-axis which is corresponding to the data.
- style: The type of icon in legend. If set to 'none', no legend item will be rendered. 'line' | 'plainline' | 'square' | 'rect'| 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye' | 'none'optional legend_type: Var[LiteralLegendType] The style of the component.
+ x_axis_id: The id of x-axis which is corresponding to the data. Default: 0
+ y_axis_id: The id of y-axis which is corresponding to the data. Default: 0
+ legend_type: The type of icon in legend. If set to 'none', no legend item will be rendered. 'line' | 'plainline' | 'square' | 'rect'| 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye' | 'none' optional
+ is_animation_active: If set false, animation of bar will be disabled. Default: True
+ animation_begin: Specifies when the animation should begin, the unit of this option is ms. Default: 0
+ animation_duration: Specifies the duration of animation, the unit of this option is ms. Default: 1500
+ animation_easing: The type of easing function. Default: "ease"
+ on_animation_start: The customized event handler of animation start
+ on_animation_end: The customized event handler of animation end
+ on_click: The customized event handler of click on the component in this group
+ on_mouse_down: The customized event handler of mousedown on the component in this group
+ on_mouse_up: The customized event handler of mouseup on the component in this group
+ on_mouse_move: The customized event handler of mousemove on the component in this group
+ on_mouse_over: The customized event handler of mouseover on the component in this group
+ on_mouse_out: The customized event handler of mouseout on the component in this group
+ on_mouse_enter: The customized event handler of mouseenter on the component in this group
+ on_mouse_leave: The customized event handler of mouseleave on the component in this group
+ style: The style of the component.
key: A unique key for the component.
id: The id for the component.
class_name: The class name for the component.
@@ -835,103 +1168,170 @@ class Line(Cartesian):
*children,
type_: Optional[
Union[
+ Literal[
+ "basis",
+ "basisClosed",
+ "basisOpen",
+ "bump",
+ "bumpX",
+ "bumpY",
+ "linear",
+ "linearClosed",
+ "monotone",
+ "monotoneX",
+ "monotoneY",
+ "natural",
+ "step",
+ "stepAfter",
+ "stepBefore",
+ ],
Var[
Literal[
"basis",
"basisClosed",
"basisOpen",
+ "bump",
"bumpX",
"bumpY",
- "bump",
"linear",
"linearClosed",
- "natural",
+ "monotone",
"monotoneX",
"monotoneY",
- "monotone",
+ "natural",
"step",
- "stepBefore",
"stepAfter",
+ "stepBefore",
]
],
- Literal[
- "basis",
- "basisClosed",
- "basisOpen",
- "bumpX",
- "bumpY",
- "bump",
- "linear",
- "linearClosed",
- "natural",
- "monotoneX",
- "monotoneY",
- "monotone",
- "step",
- "stepBefore",
- "stepAfter",
- ],
]
] = None,
- stroke: Optional[Union[Var[str], str]] = None,
- stoke_width: Optional[Union[Var[int], int]] = None,
- dot: Optional[Union[Var[bool], bool]] = None,
- active_dot: Optional[Union[Var[bool], bool]] = None,
+ stroke: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
+ stroke_width: Optional[Union[Var[int], int]] = None,
+ dot: Optional[
+ Union[Dict[str, Any], Var[Union[Dict[str, Any], bool]], bool]
+ ] = None,
+ active_dot: Optional[
+ Union[Dict[str, Any], Var[Union[Dict[str, Any], bool]], bool]
+ ] = None,
label: Optional[Union[Var[bool], bool]] = None,
hide: Optional[Union[Var[bool], bool]] = None,
connect_nulls: Optional[Union[Var[bool], bool]] = None,
+ unit: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ points: Optional[Union[List[Dict[str, Any]], Var[List[Dict[str, Any]]]]] = None,
+ stroke_dasharray: Optional[Union[Var[str], str]] = None,
layout: Optional[
Union[
- Var[Literal["horizontal", "vertical"]],
Literal["horizontal", "vertical"],
+ Var[Literal["horizontal", "vertical"]],
]
] = None,
- data_key: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- x_axis_id: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- y_axis_id: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
+ data_key: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ x_axis_id: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ y_axis_id: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ legend_type: Optional[
+ Union[
+ Literal[
+ "circle",
+ "cross",
+ "diamond",
+ "line",
+ "none",
+ "plainline",
+ "rect",
+ "square",
+ "star",
+ "triangle",
+ "wye",
+ ],
+ Var[
+ Literal[
+ "circle",
+ "cross",
+ "diamond",
+ "line",
+ "none",
+ "plainline",
+ "rect",
+ "square",
+ "star",
+ "triangle",
+ "wye",
+ ]
+ ],
+ ]
+ ] = None,
+ is_animation_active: Optional[Union[Var[bool], bool]] = None,
+ animation_begin: Optional[Union[Var[int], int]] = None,
+ animation_duration: Optional[Union[Var[int], int]] = None,
+ animation_easing: Optional[
+ Union[
+ Literal["ease", "ease-in", "ease-in-out", "ease-out", "linear"],
+ Var[Literal["ease", "ease-in", "ease-in-out", "ease-out", "linear"]],
+ ]
+ ] = None,
+ name: Optional[Union[Var[Union[int, str]], int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_animation_end: Optional[EventType[[]]] = None,
+ on_animation_start: Optional[EventType[[]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Line":
"""Create the component.
Args:
*children: The children of the component.
type_: The interpolation type of line. And customized interpolation function can be set to type. It's the same as type in Area.
- stroke: The color of the line stroke.
- stoke_width: The width of the line stroke.
- dot: The dot is shown when mouse enter a line chart and this chart has tooltip. If false set, no active dot will not be drawn. If true set, active dot will be drawn which have the props calculated internally.
- active_dot: The dot is shown when user enter an area chart and this chart has tooltip. If false set, no active dot will not be drawn. If true set, active dot will be drawn which have the props calculated internally.
- label: If false set, labels will not be drawn. If true set, labels will be drawn which have the props calculated internally.
- hide: Hides the line when true, useful when toggling visibility state via legend.
+ stroke: The color of the line stroke. Default: rx.color("accent", 9)
+ stroke_width: The width of the line stroke. Default: 1
+ dot: The dot is shown when mouse enter a line chart and this chart has tooltip. If false set, no active dot will not be drawn. If true set, active dot will be drawn which have the props calculated internally. Default: {"stroke": rx.color("accent", 10), "fill": rx.color("accent", 4)}
+ active_dot: The dot is shown when user enter an area chart and this chart has tooltip. If false set, no active dot will not be drawn. If true set, active dot will be drawn which have the props calculated internally. Default: {"stroke": rx.color("accent", 2), "fill": rx.color("accent", 10)}
+ label: If false set, labels will not be drawn. If true set, labels will be drawn which have the props calculated internally. Default: False
+ hide: Hides the line when true, useful when toggling visibility state via legend. Default: False
connect_nulls: Whether to connect a graph line across null points.
+ unit: The unit of data. This option will be used in tooltip.
+ points: The coordinates of all the points in the line, usually calculated internally.
+ stroke_dasharray: The pattern of dashes and gaps used to paint the line.
layout: The layout of bar in the chart, usually inherited from parent. 'horizontal' | 'vertical'
data_key: The key of a group of data which should be unique in an area chart.
- x_axis_id: The id of x-axis which is corresponding to the data.
- y_axis_id: The id of y-axis which is corresponding to the data.
- style: The type of icon in legend. If set to 'none', no legend item will be rendered. 'line' | 'plainline' | 'square' | 'rect'| 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye' | 'none'optional legend_type: Var[LiteralLegendType] The style of the component.
+ x_axis_id: The id of x-axis which is corresponding to the data. Default: 0
+ y_axis_id: The id of y-axis which is corresponding to the data. Default: 0
+ legend_type: The type of icon in legend. If set to 'none', no legend item will be rendered. 'line' | 'plainline' | 'square' | 'rect'| 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye' | 'none' optional
+ is_animation_active: If set false, animation of bar will be disabled. Default: True
+ animation_begin: Specifies when the animation should begin, the unit of this option is ms. Default: 0
+ animation_duration: Specifies the duration of animation, the unit of this option is ms. Default: 1500
+ animation_easing: The type of easing function. Default: "ease"
+ name: The name of data. This option will be used in tooltip and legend to represent the component. If no value was set to this option, the value of dataKey will be used alternatively.
+ on_animation_start: The customized event handler of animation start
+ on_animation_end: The customized event handler of animation end
+ on_click: The customized event handler of click on the component in this group
+ on_mouse_down: The customized event handler of mousedown on the component in this group
+ on_mouse_up: The customized event handler of mouseup on the component in this group
+ on_mouse_move: The customized event handler of mousemove on the component in this group
+ on_mouse_over: The customized event handler of mouseover on the component in this group
+ on_mouse_out: The customized event handler of mouseout on the component in this group
+ on_mouse_enter: The customized event handler of mouseenter on the component in this group
+ on_mouse_leave: The customized event handler of mouseleave on the component in this group
+ style: The style of the component.
key: A unique key for the component.
id: The id for the component.
class_name: The class name for the component.
@@ -944,89 +1344,129 @@ class Line(Cartesian):
"""
...
-class Scatter(Cartesian):
+class Scatter(Recharts):
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- data: Optional[Union[Var[List[Dict[str, Any]]], List[Dict[str, Any]]]] = None,
- z_axis_id: Optional[Union[Var[str], str]] = None,
- line: Optional[Union[Var[bool], bool]] = None,
- shape: Optional[
+ data: Optional[Union[List[Dict[str, Any]], Var[List[Dict[str, Any]]]]] = None,
+ legend_type: Optional[
Union[
+ Literal[
+ "circle",
+ "cross",
+ "diamond",
+ "line",
+ "none",
+ "plainline",
+ "rect",
+ "square",
+ "star",
+ "triangle",
+ "wye",
+ ],
Var[
Literal[
- "square",
"circle",
"cross",
"diamond",
+ "line",
+ "none",
+ "plainline",
+ "rect",
+ "square",
"star",
"triangle",
"wye",
]
],
+ ]
+ ] = None,
+ x_axis_id: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ y_axis_id: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ z_axis_id: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ line: Optional[Union[Var[bool], bool]] = None,
+ shape: Optional[
+ Union[
Literal[
- "square", "circle", "cross", "diamond", "star", "triangle", "wye"
+ "circle", "cross", "diamond", "square", "star", "triangle", "wye"
+ ],
+ Var[
+ Literal[
+ "circle",
+ "cross",
+ "diamond",
+ "square",
+ "star",
+ "triangle",
+ "wye",
+ ]
],
]
] = None,
line_type: Optional[
- Union[Var[Literal["joint", "fitting"]], Literal["joint", "fitting"]]
+ Union[Literal["fitting", "joint"], Var[Literal["fitting", "joint"]]]
] = None,
- fill: Optional[Union[Var[str], str]] = None,
- name: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- layout: Optional[
+ fill: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
+ is_animation_active: Optional[Union[Var[bool], bool]] = None,
+ animation_begin: Optional[Union[Var[int], int]] = None,
+ animation_duration: Optional[Union[Var[int], int]] = None,
+ animation_easing: Optional[
Union[
- Var[Literal["horizontal", "vertical"]],
- Literal["horizontal", "vertical"],
+ Literal["ease", "ease-in", "ease-in-out", "ease-out", "linear"],
+ Var[Literal["ease", "ease-in", "ease-in-out", "ease-out", "linear"]],
]
] = None,
- data_key: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- x_axis_id: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- y_axis_id: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Scatter":
"""Create the component.
Args:
*children: The children of the component.
data: The source data, in which each element is an object.
- z_axis_id: The id of z-axis which is corresponding to the data.
- line: If false set, line will not be drawn. If true set, line will be drawn which have the props calculated internally.
- shape: If a string set, specified symbol will be used to show scatter item. 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye'
- line_type: If 'joint' set, line will generated by just jointing all the points. If 'fitting' set, line will be generated by fitting algorithm. 'joint' | 'fitting'
- fill: The fill
- name: the name
- layout: The layout of bar in the chart, usually inherited from parent. 'horizontal' | 'vertical'
- data_key: The key of a group of data which should be unique in an area chart.
- x_axis_id: The id of x-axis which is corresponding to the data.
- y_axis_id: The id of y-axis which is corresponding to the data.
- style: The type of icon in legend. If set to 'none', no legend item will be rendered. 'line' | 'plainline' | 'square' | 'rect'| 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye' | 'none'optional legend_type: Var[LiteralLegendType] The style of the component.
+ legend_type: The type of icon in legend. If set to 'none', no legend item will be rendered. 'line' | 'plainline' | 'square' | 'rect'| 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none'. Default: "circle"
+ x_axis_id: The id of x-axis which is corresponding to the data. Default: 0
+ y_axis_id: The id of y-axis which is corresponding to the data. Default: 0
+ z_axis_id: The id of z-axis which is corresponding to the data. Default: 0
+ line: If false set, line will not be drawn. If true set, line will be drawn which have the props calculated internally. Default: False
+ shape: If a string set, specified symbol will be used to show scatter item. 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye'. Default: "circle"
+ line_type: If 'joint' set, line will generated by just jointing all the points. If 'fitting' set, line will be generated by fitting algorithm. 'joint' | 'fitting'. Default: "joint"
+ fill: The fill color of the scatter. Default: rx.color("accent", 9)
+ is_animation_active: If set false, animation of bar will be disabled. Default: True in CSR, False in SSR
+ animation_begin: Specifies when the animation should begin, the unit of this option is ms. Default: 0
+ animation_duration: Specifies the duration of animation, the unit of this option is ms. Default: 1500
+ animation_easing: The type of easing function. Default: "ease"
+ on_click: The customized event handler of click on the component in this group
+ on_mouse_down: The customized event handler of mousedown on the component in this group
+ on_mouse_up: The customized event handler of mouseup on the component in this group
+ on_mouse_move: The customized event handler of mousemove on the component in this group
+ on_mouse_over: The customized event handler of mouseover on the component in this group
+ on_mouse_out: The customized event handler of mouseout on the component in this group
+ on_mouse_enter: The customized event handler of mouseenter on the component in this group
+ on_mouse_leave: The customized event handler of mouseleave on the component in this group
+ style: The style of the component.
key: A unique key for the component.
id: The id for the component.
class_name: The class name for the component.
@@ -1039,69 +1479,110 @@ class Scatter(Cartesian):
"""
...
-class Funnel(Cartesian):
+class Funnel(Recharts):
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- data: Optional[Union[Var[List[Dict[str, Any]]], List[Dict[str, Any]]]] = None,
+ data: Optional[Union[List[Dict[str, Any]], Var[List[Dict[str, Any]]]]] = None,
+ data_key: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ name_key: Optional[Union[Var[str], str]] = None,
+ legend_type: Optional[
+ Union[
+ Literal[
+ "circle",
+ "cross",
+ "diamond",
+ "line",
+ "none",
+ "plainline",
+ "rect",
+ "square",
+ "star",
+ "triangle",
+ "wye",
+ ],
+ Var[
+ Literal[
+ "circle",
+ "cross",
+ "diamond",
+ "line",
+ "none",
+ "plainline",
+ "rect",
+ "square",
+ "star",
+ "triangle",
+ "wye",
+ ]
+ ],
+ ]
+ ] = None,
+ is_animation_active: Optional[Union[Var[bool], bool]] = None,
animation_begin: Optional[Union[Var[int], int]] = None,
animation_duration: Optional[Union[Var[int], int]] = None,
animation_easing: Optional[
Union[
- Var[Literal["ease", "ease-in", "ease-out", "ease-in-out", "linear"]],
- Literal["ease", "ease-in", "ease-out", "ease-in-out", "linear"],
+ Literal["ease", "ease-in", "ease-in-out", "ease-out", "linear"],
+ Var[Literal["ease", "ease-in", "ease-in-out", "ease-out", "linear"]],
]
] = None,
- layout: Optional[
- Union[
- Var[Literal["horizontal", "vertical"]],
- Literal["horizontal", "vertical"],
- ]
+ stroke: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
+ trapezoids: Optional[
+ Union[List[Dict[str, Any]], Var[List[Dict[str, Any]]]]
] = None,
- data_key: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- x_axis_id: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- y_axis_id: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_animation_end: Optional[EventType[[]]] = None,
+ on_animation_start: Optional[EventType[[]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Funnel":
"""Create the component.
Args:
*children: The children of the component.
data: The source data, in which each element is an object.
- animation_begin: Specifies when the animation should begin, the unit of this option is ms.
- animation_duration: Specifies the duration of animation, the unit of this option is ms.
- animation_easing: The type of easing function. 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'
- layout: The layout of bar in the chart, usually inherited from parent. 'horizontal' | 'vertical'
- data_key: The key of a group of data which should be unique in an area chart.
- x_axis_id: The id of x-axis which is corresponding to the data.
- y_axis_id: The id of y-axis which is corresponding to the data.
- style: The type of icon in legend. If set to 'none', no legend item will be rendered. 'line' | 'plainline' | 'square' | 'rect'| 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye' | 'none'optional legend_type: Var[LiteralLegendType] The style of the component.
+ data_key: The key or getter of a group of data which should be unique in a FunnelChart.
+ name_key: The key of each sector's name. Default: "name"
+ legend_type: The type of icon in legend. If set to 'none', no legend item will be rendered. Default: "line"
+ is_animation_active: If set false, animation of line will be disabled. Default: True
+ animation_begin: Specifies when the animation should begin, the unit of this option is ms. Default: 0
+ animation_duration: Specifies the duration of animation, the unit of this option is ms. Default: 1500
+ animation_easing: The type of easing function. 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'. Default "ease"
+ stroke: Stroke color. Default: rx.color("gray", 3)
+ trapezoids: The coordinates of all the trapezoids in the funnel, usually calculated internally.
+ on_animation_start: The customized event handler of animation start
+ on_animation_end: The customized event handler of animation end
+ on_click: The customized event handler of click on the component in this group
+ on_mouse_down: The customized event handler of mousedown on the component in this group
+ on_mouse_up: The customized event handler of mouseup on the component in this group
+ on_mouse_move: The customized event handler of mousemove on the component in this group
+ on_mouse_over: The customized event handler of mouseover on the component in this group
+ on_mouse_out: The customized event handler of mouseout on the component in this group
+ on_mouse_enter: The customized event handler of mouseenter on the component in this group
+ on_mouse_leave: The customized event handler of mouseleave on the component in this group
+ style: The style of the component.
key: A unique key for the component.
id: The id for the component.
class_name: The class name for the component.
@@ -1120,75 +1601,43 @@ class ErrorBar(Recharts):
def create( # type: ignore
cls,
*children,
- direction: Optional[
- Union[Var[Literal["x", "y", "both"]], Literal["x", "y", "both"]]
- ] = None,
- data_key: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
+ direction: Optional[Union[Literal["x", "y"], Var[Literal["x", "y"]]]] = None,
+ data_key: Optional[Union[Var[Union[int, str]], int, str]] = None,
width: Optional[Union[Var[int], int]] = None,
- stroke: Optional[Union[Var[str], str]] = None,
- stroke_width: Optional[Union[Var[int], int]] = None,
+ stroke: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
+ stroke_width: Optional[Union[Var[Union[float, int]], float, int]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ErrorBar":
"""Create the component.
Args:
*children: The children of the component.
- direction: The direction of error bar. 'x' | 'y' | 'both'
+ direction: Only used for ScatterChart with error bars in two directions. Only accepts a value of "x" or "y" and makes the error bars lie in that direction.
data_key: The key of a group of data which should be unique in an area chart.
- width: The width of the error bar ends.
- stroke: The stroke color of error bar.
- stroke_width: The stroke width of error bar.
+ width: The width of the error bar ends. Default: 5
+ stroke: The stroke color of error bar. Default: rx.color("gray", 8)
+ stroke_width: The stroke width of error bar. Default: 1.5
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -1208,16 +1657,15 @@ class Reference(Recharts):
def create( # type: ignore
cls,
*children,
- x_axis_id: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- y_axis_id: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- x: Optional[Union[Var[str], str]] = None,
- y: Optional[Union[Var[str], str]] = None,
+ x_axis_id: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ y_axis_id: Optional[Union[Var[Union[int, str]], int, str]] = None,
if_overflow: Optional[
Union[
- Var[Literal["discard", "hidden", "visible", "extendDomain"]],
- Literal["discard", "hidden", "visible", "extendDomain"],
+ Literal["discard", "extendDomain", "hidden", "visible"],
+ Var[Literal["discard", "extendDomain", "hidden", "visible"]],
]
] = None,
+ label: Optional[Union[Var[Union[int, str]], int, str]] = None,
is_front: Optional[Union[Var[bool], bool]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
@@ -1225,63 +1673,32 @@ class Reference(Recharts):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Reference":
"""Create the component.
Args:
*children: The children of the component.
- x_axis_id: The id of x-axis which is corresponding to the data.
- y_axis_id: The id of y-axis which is corresponding to the data.
- x: If set a string or a number, a vertical line perpendicular to the x-axis specified by xAxisId will be drawn. If the specified x-axis is a number axis, the type of x must be Number. If the specified x-axis is a category axis, the value of x must be one of the categorys, otherwise no line will be drawn.
- y: If set a string or a number, a horizontal line perpendicular to the y-axis specified by yAxisId will be drawn. If the specified y-axis is a number axis, the type of y must be Number. If the specified y-axis is a category axis, the value of y must be one of the categorys, otherwise no line will be drawn.
- if_overflow: Defines how to draw the reference line if it falls partly outside the canvas. If set to 'discard', the reference line will not be drawn at all. If set to 'hidden', the reference line will be clipped to the canvas. If set to 'visible', the reference line will be drawn completely. If set to 'extendDomain', the domain of the overflown axis will be extended such that the reference line fits into the canvas.
- is_front: If set true, the line will be rendered in front of bars in BarChart, etc.
+ x_axis_id: The id of x-axis which is corresponding to the data. Default: 0
+ y_axis_id: The id of y-axis which is corresponding to the data. Default: 0
+ if_overflow: Defines how to draw the reference line if it falls partly outside the canvas. If set to 'discard', the reference line will not be drawn at all. If set to 'hidden', the reference line will be clipped to the canvas. If set to 'visible', the reference line will be drawn completely. If set to 'extendDomain', the domain of the overflown axis will be extended such that the reference line fits into the canvas. Default: "discard"
+ label: If set a string or a number, default label will be drawn, and the option is content.
+ is_front: If set true, the line will be rendered in front of bars in BarChart, etc. Default: False
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -1301,17 +1718,20 @@ class ReferenceLine(Reference):
def create( # type: ignore
cls,
*children,
- stroke_width: Optional[Union[Var[int], int]] = None,
- x_axis_id: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- y_axis_id: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- x: Optional[Union[Var[str], str]] = None,
- y: Optional[Union[Var[str], str]] = None,
+ x: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ y: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ stroke: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
+ stroke_width: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ segment: Optional[List[Any]] = None,
+ x_axis_id: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ y_axis_id: Optional[Union[Var[Union[int, str]], int, str]] = None,
if_overflow: Optional[
Union[
- Var[Literal["discard", "hidden", "visible", "extendDomain"]],
- Literal["discard", "hidden", "visible", "extendDomain"],
+ Literal["discard", "extendDomain", "hidden", "visible"],
+ Var[Literal["discard", "extendDomain", "hidden", "visible"]],
]
] = None,
+ label: Optional[Union[Var[Union[int, str]], int, str]] = None,
is_front: Optional[Union[Var[bool], bool]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
@@ -1319,64 +1739,37 @@ class ReferenceLine(Reference):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ReferenceLine":
"""Create the component.
Args:
*children: The children of the component.
- stroke_width: The width of the stroke.
- x_axis_id: The id of x-axis which is corresponding to the data.
- y_axis_id: The id of y-axis which is corresponding to the data.
x: If set a string or a number, a vertical line perpendicular to the x-axis specified by xAxisId will be drawn. If the specified x-axis is a number axis, the type of x must be Number. If the specified x-axis is a category axis, the value of x must be one of the categorys, otherwise no line will be drawn.
y: If set a string or a number, a horizontal line perpendicular to the y-axis specified by yAxisId will be drawn. If the specified y-axis is a number axis, the type of y must be Number. If the specified y-axis is a category axis, the value of y must be one of the categorys, otherwise no line will be drawn.
- if_overflow: Defines how to draw the reference line if it falls partly outside the canvas. If set to 'discard', the reference line will not be drawn at all. If set to 'hidden', the reference line will be clipped to the canvas. If set to 'visible', the reference line will be drawn completely. If set to 'extendDomain', the domain of the overflown axis will be extended such that the reference line fits into the canvas.
- is_front: If set true, the line will be rendered in front of bars in BarChart, etc.
+ stroke: The color of the reference line.
+ stroke_width: The width of the stroke. Default: 1
+ segment: Array of endpoints in { x, y } format. These endpoints would be used to draw the ReferenceLine.
+ x_axis_id: The id of x-axis which is corresponding to the data. Default: 0
+ y_axis_id: The id of y-axis which is corresponding to the data. Default: 0
+ if_overflow: Defines how to draw the reference line if it falls partly outside the canvas. If set to 'discard', the reference line will not be drawn at all. If set to 'hidden', the reference line will be clipped to the canvas. If set to 'visible', the reference line will be drawn completely. If set to 'extendDomain', the domain of the overflown axis will be extended such that the reference line fits into the canvas. Default: "discard"
+ label: If set a string or a number, default label will be drawn, and the option is content.
+ is_front: If set true, the line will be rendered in front of bars in BarChart, etc. Default: False
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -1391,22 +1784,25 @@ class ReferenceLine(Reference):
...
class ReferenceDot(Reference):
- def get_event_triggers(self) -> dict[str, Union[Var, Any]]: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- x_axis_id: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- y_axis_id: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- x: Optional[Union[Var[str], str]] = None,
- y: Optional[Union[Var[str], str]] = None,
+ x: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ y: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ r: Optional[Union[Var[int], int]] = None,
+ fill: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
+ stroke: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
+ x_axis_id: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ y_axis_id: Optional[Union[Var[Union[int, str]], int, str]] = None,
if_overflow: Optional[
Union[
- Var[Literal["discard", "hidden", "visible", "extendDomain"]],
- Literal["discard", "hidden", "visible", "extendDomain"],
+ Literal["discard", "extendDomain", "hidden", "visible"],
+ Var[Literal["discard", "extendDomain", "hidden", "visible"]],
]
] = None,
+ label: Optional[Union[Var[Union[int, str]], int, str]] = None,
is_front: Optional[Union[Var[bool], bool]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
@@ -1414,36 +1810,45 @@ class ReferenceDot(Reference):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ReferenceDot":
"""Create the component.
Args:
*children: The children of the component.
- x_axis_id: The id of x-axis which is corresponding to the data.
- y_axis_id: The id of y-axis which is corresponding to the data.
x: If set a string or a number, a vertical line perpendicular to the x-axis specified by xAxisId will be drawn. If the specified x-axis is a number axis, the type of x must be Number. If the specified x-axis is a category axis, the value of x must be one of the categorys, otherwise no line will be drawn.
y: If set a string or a number, a horizontal line perpendicular to the y-axis specified by yAxisId will be drawn. If the specified y-axis is a number axis, the type of y must be Number. If the specified y-axis is a category axis, the value of y must be one of the categorys, otherwise no line will be drawn.
- if_overflow: Defines how to draw the reference line if it falls partly outside the canvas. If set to 'discard', the reference line will not be drawn at all. If set to 'hidden', the reference line will be clipped to the canvas. If set to 'visible', the reference line will be drawn completely. If set to 'extendDomain', the domain of the overflown axis will be extended such that the reference line fits into the canvas.
- is_front: If set true, the line will be rendered in front of bars in BarChart, etc.
+ r: The radius of dot.
+ fill: The color of the area fill.
+ stroke: The color of the line stroke.
+ on_click: The customized event handler of click on the component in this chart
+ on_mouse_down: The customized event handler of mousedown on the component in this chart
+ on_mouse_up: The customized event handler of mouseup on the component in this chart
+ on_mouse_over: The customized event handler of mouseover on the component in this chart
+ on_mouse_out: The customized event handler of mouseout on the component in this chart
+ on_mouse_enter: The customized event handler of mouseenter on the component in this chart
+ on_mouse_move: The customized event handler of mousemove on the component in this chart
+ on_mouse_leave: The customized event handler of mouseleave on the component in this chart
+ x_axis_id: The id of x-axis which is corresponding to the data. Default: 0
+ y_axis_id: The id of y-axis which is corresponding to the data. Default: 0
+ if_overflow: Defines how to draw the reference line if it falls partly outside the canvas. If set to 'discard', the reference line will not be drawn at all. If set to 'hidden', the reference line will be clipped to the canvas. If set to 'visible', the reference line will be drawn completely. If set to 'extendDomain', the domain of the overflown axis will be extended such that the reference line fits into the canvas. Default: "discard"
+ label: If set a string or a number, default label will be drawn, and the option is content.
+ is_front: If set true, the line will be rendered in front of bars in BarChart, etc. Default: False
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -1463,19 +1868,19 @@ class ReferenceArea(Recharts):
def create( # type: ignore
cls,
*children,
- stroke: Optional[Union[Var[str], str]] = None,
- fill: Optional[Union[Var[str], str]] = None,
+ stroke: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
+ fill: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
fill_opacity: Optional[Union[Var[float], float]] = None,
- x_axis_id: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- y_axis_id: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- x1: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- x2: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- y1: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- y2: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
+ x_axis_id: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ y_axis_id: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ x1: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ x2: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ y1: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ y2: Optional[Union[Var[Union[int, str]], int, str]] = None,
if_overflow: Optional[
Union[
- Var[Literal["discard", "hidden", "visible", "extendDomain"]],
- Literal["discard", "hidden", "visible", "extendDomain"],
+ Literal["discard", "extendDomain", "hidden", "visible"],
+ Var[Literal["discard", "extendDomain", "hidden", "visible"]],
]
] = None,
is_front: Optional[Union[Var[bool], bool]] = None,
@@ -1485,52 +1890,22 @@ class ReferenceArea(Recharts):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ReferenceArea":
"""Create the component.
@@ -1545,8 +1920,8 @@ class ReferenceArea(Recharts):
x2: A boundary value of the area. If the specified x-axis is a number axis, the type of x must be Number. If the specified x-axis is a category axis, the value of x must be one of the categorys. If one of x1 or x2 is invalidate, the area will cover along x-axis.
y1: A boundary value of the area. If the specified y-axis is a number axis, the type of y must be Number. If the specified y-axis is a category axis, the value of y must be one of the categorys. If one of y1 or y2 is invalidate, the area will cover along y-axis.
y2: A boundary value of the area. If the specified y-axis is a number axis, the type of y must be Number. If the specified y-axis is a category axis, the value of y must be one of the categorys. If one of y1 or y2 is invalidate, the area will cover along y-axis.
- if_overflow: Defines how to draw the reference line if it falls partly outside the canvas. If set to 'discard', the reference line will not be drawn at all. If set to 'hidden', the reference line will be clipped to the canvas. If set to 'visible', the reference line will be drawn completely. If set to 'extendDomain', the domain of the overflown axis will be extended such that the reference line fits into the canvas.
- is_front: If set true, the line will be rendered in front of bars in BarChart, etc.
+ if_overflow: Defines how to draw the reference line if it falls partly outside the canvas. If set to 'discard', the reference line will not be drawn at all. If set to 'hidden', the reference line will be clipped to the canvas. If set to 'visible', the reference line will be drawn completely. If set to 'extendDomain', the domain of the overflown axis will be extended such that the reference line fits into the canvas. Default: "discard"
+ is_front: If set true, the line will be rendered in front of bars in BarChart, etc. Default: False
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -1576,61 +1951,31 @@ class Grid(Recharts):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Grid":
"""Create the component.
Args:
*children: The children of the component.
- x: The x-coordinate of grid.
- y: The y-coordinate of grid.
- width: The width of grid.
- height: The height of grid.
+ x: The x-coordinate of grid. Default: 0
+ y: The y-coordinate of grid. Default: 0
+ width: The width of grid. Default: 0
+ height: The height of grid. Default: 0
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -1650,11 +1995,18 @@ class CartesianGrid(Grid):
def create( # type: ignore
cls,
*children,
- horizontal: Optional[Union[Var[Dict[str, Any]], Dict[str, Any]]] = None,
- vertical: Optional[Union[Var[Dict[str, Any]], Dict[str, Any]]] = None,
- fill: Optional[Union[Var[str], str]] = None,
+ horizontal: Optional[Union[Var[bool], bool]] = None,
+ vertical: Optional[Union[Var[bool], bool]] = None,
+ vertical_points: Optional[
+ Union[List[Union[int, str]], Var[List[Union[int, str]]]]
+ ] = None,
+ horizontal_points: Optional[
+ Union[List[Union[int, str]], Var[List[Union[int, str]]]]
+ ] = None,
+ fill: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
fill_opacity: Optional[Union[Var[float], float]] = None,
stroke_dasharray: Optional[Union[Var[str], str]] = None,
+ stroke: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
x: Optional[Union[Var[int], int]] = None,
y: Optional[Union[Var[int], int]] = None,
width: Optional[Union[Var[int], int]] = None,
@@ -1665,66 +2017,39 @@ class CartesianGrid(Grid):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "CartesianGrid":
"""Create the component.
Args:
*children: The children of the component.
- horizontal: The horizontal line configuration.
- vertical: The vertical line configuration.
+ horizontal: The horizontal line configuration. Default: True
+ vertical: The vertical line configuration. Default: True
+ vertical_points: The x-coordinates in pixel values of all vertical lines. Default: []
+ horizontal_points: The x-coordinates in pixel values of all vertical lines. Default: []
fill: The background of grid.
- fill_opacity: The opacity of the background used to fill the space between grid lines
- stroke_dasharray: The pattern of dashes and gaps used to paint the lines of the grid
- x: The x-coordinate of grid.
- y: The y-coordinate of grid.
- width: The width of grid.
- height: The height of grid.
+ fill_opacity: The opacity of the background used to fill the space between grid lines.
+ stroke_dasharray: The pattern of dashes and gaps used to paint the lines of the grid.
+ stroke: the stroke color of grid. Default: rx.color("gray", 7)
+ x: The x-coordinate of grid. Default: 0
+ y: The y-coordinate of grid. Default: 0
+ width: The width of grid. Default: 0
+ height: The height of grid. Default: 0
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -1746,21 +2071,22 @@ class CartesianAxis(Grid):
*children,
orientation: Optional[
Union[
- Var[Literal["top", "bottom", "left", "right"]],
- Literal["top", "bottom", "left", "right"],
+ Literal["bottom", "left", "right", "top"],
+ Var[Literal["bottom", "left", "right", "top"]],
]
] = None,
+ view_box: Optional[Union[Dict[str, Any], Var[Dict[str, Any]]]] = None,
axis_line: Optional[Union[Var[bool], bool]] = None,
+ tick: Optional[Union[Var[bool], bool]] = None,
tick_line: Optional[Union[Var[bool], bool]] = None,
tick_size: Optional[Union[Var[int], int]] = None,
interval: Optional[
Union[
- Var[Literal["preserveStart", "preserveEnd", "preserveStartEnd"]],
- Literal["preserveStart", "preserveEnd", "preserveStartEnd"],
+ Literal["preserveEnd", "preserveStart", "preserveStartEnd"],
+ Var[Literal["preserveEnd", "preserveStart", "preserveStartEnd"]],
]
] = None,
- ticks: Optional[Union[Var[bool], bool]] = None,
- label: Optional[Union[Var[str], str]] = None,
+ label: Optional[Union[Var[Union[int, str]], int, str]] = None,
mirror: Optional[Union[Var[bool], bool]] = None,
tick_margin: Optional[Union[Var[int], int]] = None,
x: Optional[Union[Var[int], int]] = None,
@@ -1773,70 +2099,41 @@ class CartesianAxis(Grid):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "CartesianAxis":
"""Create the component.
Args:
*children: The children of the component.
- orientation: The orientation of axis 'top' | 'bottom' | 'left' | 'right'
- axis_line: If set false, no axis line will be drawn. If set a object, the option is the configuration of axis line.
- tick_line: If set false, no axis tick lines will be drawn. If set a object, the option is the configuration of tick lines.
- tick_size: The length of tick line.
- interval: If set 0, all the ticks will be shown. If set preserveStart", "preserveEnd" or "preserveStartEnd", the ticks which is to be shown or hidden will be calculated automatically.
- ticks: If set false, no ticks will be drawn.
+ orientation: The orientation of axis 'top' | 'bottom' | 'left' | 'right'. Default: "bottom"
+ view_box: The box of viewing area. Default: {"x": 0, "y": 0, "width": 0, "height": 0}
+ axis_line: If set false, no axis line will be drawn. If set a object, the option is the configuration of axis line. Default: True
+ tick: If set false, no ticks will be drawn.
+ tick_line: If set false, no axis tick lines will be drawn. If set a object, the option is the configuration of tick lines. Default: True
+ tick_size: The length of tick line. Default: 6
+ interval: If set 0, all the ticks will be shown. If set preserveStart", "preserveEnd" or "preserveStartEnd", the ticks which is to be shown or hidden will be calculated automatically. Default: "preserveEnd"
label: If set a string or a number, default label will be drawn, and the option is content.
- mirror: If set true, flips ticks around the axis line, displaying the labels inside the chart instead of outside.
+ mirror: If set true, flips ticks around the axis line, displaying the labels inside the chart instead of outside. Default: False
tick_margin: The margin between tick line and tick.
- x: The x-coordinate of grid.
- y: The y-coordinate of grid.
- width: The width of grid.
- height: The height of grid.
+ x: The x-coordinate of grid. Default: 0
+ y: The y-coordinate of grid. Default: 0
+ width: The width of grid. Default: 0
+ height: The height of grid. Default: 0
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -1849,3 +2146,19 @@ class CartesianAxis(Grid):
The component.
"""
...
+
+area = Area.create
+bar = Bar.create
+line = Line.create
+scatter = Scatter.create
+x_axis = XAxis.create
+y_axis = YAxis.create
+z_axis = ZAxis.create
+brush = Brush.create
+cartesian_axis = CartesianAxis.create
+cartesian_grid = CartesianGrid.create
+reference_line = ReferenceLine.create
+reference_dot = ReferenceDot.create
+reference_area = ReferenceArea.create
+error_bar = ErrorBar.create
+funnel = Funnel.create
diff --git a/reflex/components/recharts/charts.py b/reflex/components/recharts/charts.py
index 5a29cc2aa..d7e07b2d8 100644
--- a/reflex/components/recharts/charts.py
+++ b/reflex/components/recharts/charts.py
@@ -1,4 +1,5 @@
"""A module that defines the chart components in Recharts."""
+
from __future__ import annotations
from typing import Any, Dict, List, Union
@@ -6,7 +7,9 @@ from typing import Any, Dict, List, Union
from reflex.components.component import Component
from reflex.components.recharts.general import ResponsiveContainer
from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.constants.colors import Color
+from reflex.event import EventHandler, empty_event
+from reflex.vars.base import Var
from .recharts import (
LiteralAnimationEasing,
@@ -21,42 +24,23 @@ from .recharts import (
class ChartBase(RechartsCharts):
"""A component that wraps a Recharts charts."""
- # The source data, in which each element is an object.
- data: Var[List[Dict[str, Any]]]
-
- # If any two categorical charts(rx.line_chart, rx.area_chart, rx.bar_chart, rx.composed_chart) have the same sync_id, these two charts can sync the position GraphingTooltip, and the start_index, end_index of Brush.
- sync_id: Var[str]
-
- # When sync_id is provided, allows customisation of how the charts will synchronize GraphingTooltips and brushes. Using 'index' (default setting), other charts will reuse current datum's index within the data array. In cases where data does not have the same length, this might yield unexpected results. In that case use 'value' which will try to match other charts values, or a fully custom function which will receive tick, data as argument and should return an index. 'index' | 'value' | function
- sync_method: Var[LiteralSyncMethod]
-
# The width of chart container. String or Integer
width: Var[Union[str, int]] = "100%" # type: ignore
# The height of chart container.
height: Var[Union[str, int]] = "100%" # type: ignore
- # The layout of area in the chart. 'horizontal' | 'vertical'
- layout: Var[LiteralLayout]
+ # The customized event handler of click on the component in this chart
+ on_click: EventHandler[empty_event]
- # The sizes of whitespace around the chart.
- margin: Var[Dict[str, Any]]
+ # The customized event handler of mouseenter on the component in this chart
+ on_mouse_enter: EventHandler[empty_event]
- # The type of offset function used to generate the lower and upper values in the series array. The four types are built-in offsets in d3-shape. 'expand' | 'none' | 'wiggle' | 'silhouette'
- stack_offset: Var[LiteralStackOffset]
+ # The customized event handler of mousemove on the component in this chart
+ on_mouse_move: EventHandler[empty_event]
- def get_event_triggers(self) -> dict[str, Union[Var, Any]]:
- """Get the event triggers that pass the component's value to the handler.
-
- Returns:
- A dict mapping the event trigger to the var that is passed to the handler.
- """
- return {
- EventTriggers.ON_CLICK: lambda: [],
- EventTriggers.ON_MOUSE_ENTER: lambda: [],
- EventTriggers.ON_MOUSE_MOVE: lambda: [],
- EventTriggers.ON_MOUSE_LEAVE: lambda: [],
- }
+ # The customized event handler of mouseleave on the component in this chart
+ on_mouse_leave: EventHandler[empty_event]
@staticmethod
def _ensure_valid_dimension(name: str, value: Any) -> None:
@@ -116,19 +100,38 @@ class ChartBase(RechartsCharts):
)
-class AreaChart(ChartBase):
+class CategoricalChartBase(ChartBase):
+ """A component that wraps a Categorical Recharts charts."""
+
+ # The source data, in which each element is an object.
+ data: Var[List[Dict[str, Any]]]
+
+ # The sizes of whitespace around the chart, i.e. {"top": 50, "right": 30, "left": 20, "bottom": 5}.
+ margin: Var[Dict[str, Any]]
+
+ # If any two categorical charts(rx.line_chart, rx.area_chart, rx.bar_chart, rx.composed_chart) have the same sync_id, these two charts can sync the position GraphingTooltip, and the start_index, end_index of Brush.
+ sync_id: Var[str]
+
+ # When sync_id is provided, allows customisation of how the charts will synchronize GraphingTooltips and brushes. Using 'index' (default setting), other charts will reuse current datum's index within the data array. In cases where data does not have the same length, this might yield unexpected results. In that case use 'value' which will try to match other charts values, or a fully custom function which will receive tick, data as argument and should return an index. 'index' | 'value' | function. Default: "index"
+ sync_method: Var[LiteralSyncMethod]
+
+ # The layout of area in the chart. 'horizontal' | 'vertical'. Default: "horizontal"
+ layout: Var[LiteralLayout]
+
+ # The type of offset function used to generate the lower and upper values in the series array. The four types are built-in offsets in d3-shape. 'expand' | 'none' | 'wiggle' | 'silhouette'
+ stack_offset: Var[LiteralStackOffset]
+
+
+class AreaChart(CategoricalChartBase):
"""An Area chart component in Recharts."""
tag = "AreaChart"
alias = "RechartsAreaChart"
- # The base value of area. Number | 'dataMin' | 'dataMax' | 'auto'
+ # The base value of area. Number | 'dataMin' | 'dataMax' | 'auto'. Default: "auto"
base_value: Var[Union[int, LiteralComposedChartBaseValue]]
- # The type of offset function used to generate the lower and upper values in the series array. The four types are built-in offsets in d3-shape.
- stack_offset: Var[LiteralStackOffset]
-
# Valid children components
_valid_children: List[str] = [
"XAxis",
@@ -141,21 +144,22 @@ class AreaChart(ChartBase):
"Legend",
"GraphingTooltip",
"Area",
+ "Defs",
]
-class BarChart(ChartBase):
+class BarChart(CategoricalChartBase):
"""A Bar chart component in Recharts."""
tag = "BarChart"
alias = "RechartsBarChart"
- # The gap between two bar categories, which can be a percent value or a fixed value. Percentage | Number
- bar_category_gap: Var[Union[str, int]] # type: ignore
+ # The gap between two bar categories, which can be a percent value or a fixed value. Percentage | Number. Default: "10%"
+ bar_category_gap: Var[Union[str, int]]
- # The gap between two bars in the same category, which can be a percent value or a fixed value. Percentage | Number
- bar_gap: Var[Union[str, int]] # type: ignore
+ # The gap between two bars in the same category, which can be a percent value or a fixed value. Percentage | Number. Default: 4
+ bar_gap: Var[Union[str, int]]
# The width of all the bars in the chart. Number
bar_size: Var[int]
@@ -163,10 +167,10 @@ class BarChart(ChartBase):
# The maximum width of all the bars in a horizontal BarChart, or maximum height in a vertical BarChart.
max_bar_size: Var[int]
- # The type of offset function used to generate the lower and upper values in the series array. The four types are built-in offsets in d3-shape.
+ # The type of offset function used to generate the lower and upper values in the series array. The four types are built-in offsets in d3-shape. Default: "none"
stack_offset: Var[LiteralStackOffset]
- # If false set, stacked items will be rendered left to right. If true set, stacked items will be rendered right to left. (Render direction affects SVG layering, not x position.)
+ # If false set, stacked items will be rendered left to right. If true set, stacked items will be rendered right to left. (Render direction affects SVG layering, not x position.) Default: False
reverse_stack_order: Var[bool]
# Valid children components
@@ -184,7 +188,7 @@ class BarChart(ChartBase):
]
-class LineChart(ChartBase):
+class LineChart(CategoricalChartBase):
"""A Line chart component in Recharts."""
tag = "LineChart"
@@ -206,26 +210,26 @@ class LineChart(ChartBase):
]
-class ComposedChart(ChartBase):
+class ComposedChart(CategoricalChartBase):
"""A Composed chart component in Recharts."""
tag = "ComposedChart"
alias = "RechartsComposedChart"
- # The base value of area. Number | 'dataMin' | 'dataMax' | 'auto'
+ # The base value of area. Number | 'dataMin' | 'dataMax' | 'auto'. Default: "auto"
base_value: Var[Union[int, LiteralComposedChartBaseValue]]
- # The gap between two bar categories, which can be a percent value or a fixed value. Percentage | Number
- bar_category_gap: Var[Union[str, int]] # type: ignore
+ # The gap between two bar categories, which can be a percent value or a fixed value. Percentage | Number. Default: "10%"
+ bar_category_gap: Var[Union[str, int]]
- # The gap between two bars in the same category, which can be a percent value or a fixed value. Percentage | Number
+ # The gap between two bars in the same category. Default: 4
bar_gap: Var[int]
- # The width of all the bars in the chart. Number
+ # The width or height of each bar. If the barSize is not specified, the size of the bar will be calculated by the barCategoryGap, barGap and the quantity of bar groups.
bar_size: Var[int]
- # If false set, stacked items will be rendered left to right. If true set, stacked items will be rendered right to left. (Render direction affects SVG layering, not x position.)
+ # If false set, stacked items will be rendered left to right. If true set, stacked items will be rendered right to left. (Render direction affects SVG layering, not x position). Default: False
reverse_stack_order: Var[bool]
# Valid children components
@@ -252,6 +256,9 @@ class PieChart(ChartBase):
alias = "RechartsPieChart"
+ # The sizes of whitespace around the chart, i.e. {"top": 50, "right": 30, "left": 20, "bottom": 5}.
+ margin: Var[Dict[str, Any]]
+
# Valid children components
_valid_children: List[str] = [
"PolarAngleAxis",
@@ -262,17 +269,17 @@ class PieChart(ChartBase):
"Pie",
]
- def get_event_triggers(self) -> dict[str, Union[Var, Any]]:
- """Get the event triggers that pass the component's value to the handler.
+ # The customized event handler of mousedown on the sectors in this group
+ on_mouse_down: EventHandler[empty_event]
- Returns:
- A dict mapping the event trigger to the var that is passed to the handler.
- """
- return {
- EventTriggers.ON_CLICK: lambda: [],
- EventTriggers.ON_MOUSE_ENTER: lambda: [],
- EventTriggers.ON_MOUSE_LEAVE: lambda: [],
- }
+ # The customized event handler of mouseup on the sectors in this group
+ on_mouse_up: EventHandler[empty_event]
+
+ # The customized event handler of mouseover on the sectors in this group
+ on_mouse_over: EventHandler[empty_event]
+
+ # The customized event handler of mouseout on the sectors in this group
+ on_mouse_out: EventHandler[empty_event]
class RadarChart(ChartBase):
@@ -282,22 +289,28 @@ class RadarChart(ChartBase):
alias = "RechartsRadarChart"
- # The The x-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of width. Number | Percentage
+ # The source data, in which each element is an object.
+ data: Var[List[Dict[str, Any]]]
+
+ # The sizes of whitespace around the chart, i.e. {"top": 50, "right": 30, "left": 20, "bottom": 5}. Default: {"top": 0, "right": 0, "left": 0, "bottom": 0}
+ margin: Var[Dict[str, Any]]
+
+ # The The x-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of width. Number | Percentage. Default: "50%"
cx: Var[Union[int, str]]
- # The The y-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of height. Number | Percentage
+ # The The y-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of height. Number | Percentage. Default: "50%"
cy: Var[Union[int, str]]
- # The angle of first radial direction line.
+ # The angle of first radial direction line. Default: 90
start_angle: Var[int]
- # The angle of last point in the circle which should be startAngle - 360 or startAngle + 360. We'll calculate the direction of chart by 'startAngle' and 'endAngle'.
+ # The angle of last point in the circle which should be startAngle - 360 or startAngle + 360. We'll calculate the direction of chart by 'startAngle' and 'endAngle'. Default: -270
end_angle: Var[int]
- # The inner radius of first circle grid. If set a percentage, the final value is obtained by multiplying the percentage of maxRadius which is calculated by the width, height, cx, cy. Number | Percentage
+ # The inner radius of first circle grid. If set a percentage, the final value is obtained by multiplying the percentage of maxRadius which is calculated by the width, height, cx, cy. Number | Percentage. Default: 0
inner_radius: Var[Union[int, str]]
- # The outer radius of last circle grid. If set a percentage, the final value is obtained by multiplying the percentage of maxRadius which is calculated by the width, height, cx, cy. Number | Percentage
+ # The outer radius of last circle grid. If set a percentage, the final value is obtained by multiplying the percentage of maxRadius which is calculated by the width, height, cx, cy. Number | Percentage. Default: "80%"
outer_radius: Var[Union[int, str]]
# Valid children components
@@ -317,10 +330,9 @@ class RadarChart(ChartBase):
A dict mapping the event trigger to the var that is passed to the handler.
"""
return {
- EventTriggers.ON_CLICK: lambda: [],
- EventTriggers.ON_MOUSE_ENTER: lambda: [],
- EventTriggers.ON_MOUSE_MOVE: lambda: [],
- EventTriggers.ON_MOUSE_LEAVE: lambda: [],
+ EventTriggers.ON_CLICK: empty_event,
+ EventTriggers.ON_MOUSE_ENTER: empty_event,
+ EventTriggers.ON_MOUSE_LEAVE: empty_event,
}
@@ -331,28 +343,34 @@ class RadialBarChart(ChartBase):
alias = "RechartsRadialBarChart"
- # The The x-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of width. Number | Percentage
+ # The source data which each element is an object.
+ data: Var[List[Dict[str, Any]]]
+
+ # The sizes of whitespace around the chart. Default: {"top": 5, "right": 5, "left": 5 "bottom": 5}
+ margin: Var[Dict[str, Any]]
+
+ # The The x-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of width. Number | Percentage. Default: "50%"
cx: Var[Union[int, str]]
- # The The y-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of height. Number | Percentage
+ # The The y-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of height. Number | Percentage. Default: "50%"
cy: Var[Union[int, str]]
- # The angle of first radial direction line.
+ # The angle of first radial direction line. Default: 0
start_angle: Var[int]
- # The angle of last point in the circle which should be startAngle - 360 or startAngle + 360. We'll calculate the direction of chart by 'startAngle' and 'endAngle'.
+ # The angle of last point in the circle which should be startAngle - 360 or startAngle + 360. We'll calculate the direction of chart by 'startAngle' and 'endAngle'. Default: 360
end_angle: Var[int]
- # The inner radius of first circle grid. If set a percentage, the final value is obtained by multiplying the percentage of maxRadius which is calculated by the width, height, cx, cy. Number | Percentage
+ # The inner radius of first circle grid. If set a percentage, the final value is obtained by multiplying the percentage of maxRadius which is calculated by the width, height, cx, cy. Number | Percentage. Default: "30%"
inner_radius: Var[Union[int, str]]
- # The outer radius of last circle grid. If set a percentage, the final value is obtained by multiplying the percentage of maxRadius which is calculated by the width, height, cx, cy. Number | Percentage
+ # The outer radius of last circle grid. If set a percentage, the final value is obtained by multiplying the percentage of maxRadius which is calculated by the width, height, cx, cy. Number | Percentage. Default: "100%"
outer_radius: Var[Union[int, str]]
- # The gap between two bar categories, which can be a percent value or a fixed value. Percentage | Number
+ # The gap between two bar categories, which can be a percent value or a fixed value. Percentage | Number. Default: "10%"
bar_category_gap: Var[Union[int, str]]
- # The gap between two bars in the same category, which can be a percent value or a fixed value. Percentage | Number
+ # The gap between two bars in the same category, which can be a percent value or a fixed value. Percentage | Number. Default: 4
bar_gap: Var[str]
# The size of each bar. If the barSize is not specified, the size of bar will be calculated by the barCategoryGap, barGap and the quantity of bar groups.
@@ -368,19 +386,6 @@ class RadialBarChart(ChartBase):
"RadialBar",
]
- def get_event_triggers(self) -> dict[str, Union[Var, Any]]:
- """Get the event triggers that pass the component's value to the handler.
-
- Returns:
- A dict mapping the event trigger to the var that is passed to the handler.
- """
- return {
- EventTriggers.ON_CLICK: lambda: [],
- EventTriggers.ON_MOUSE_ENTER: lambda: [],
- EventTriggers.ON_MOUSE_MOVE: lambda: [],
- EventTriggers.ON_MOUSE_LEAVE: lambda: [],
- }
-
class ScatterChart(ChartBase):
"""A Scatter chart component in Recharts."""
@@ -389,6 +394,9 @@ class ScatterChart(ChartBase):
alias = "RechartsScatterChart"
+ # The sizes of whitespace around the chart. Default: {"top": 5, "right": 5, "bottom": 5, "left": 5}
+ margin: Var[Dict[str, Any]]
+
# Valid children components
_valid_children: List[str] = [
"XAxis",
@@ -411,65 +419,36 @@ class ScatterChart(ChartBase):
A dict mapping the event trigger to the var that is passed to the handler.
"""
return {
- EventTriggers.ON_CLICK: lambda: [],
- EventTriggers.ON_MOUSE_OVER: lambda: [],
- EventTriggers.ON_MOUSE_OUT: lambda: [],
- EventTriggers.ON_MOUSE_ENTER: lambda: [],
- EventTriggers.ON_MOUSE_MOVE: lambda: [],
- EventTriggers.ON_MOUSE_LEAVE: lambda: [],
+ EventTriggers.ON_CLICK: empty_event,
+ EventTriggers.ON_MOUSE_DOWN: empty_event,
+ EventTriggers.ON_MOUSE_UP: empty_event,
+ EventTriggers.ON_MOUSE_MOVE: empty_event,
+ EventTriggers.ON_MOUSE_OVER: empty_event,
+ EventTriggers.ON_MOUSE_OUT: empty_event,
+ EventTriggers.ON_MOUSE_ENTER: empty_event,
+ EventTriggers.ON_MOUSE_LEAVE: empty_event,
}
-class FunnelChart(RechartsCharts):
+class FunnelChart(ChartBase):
"""A Funnel chart component in Recharts."""
tag = "FunnelChart"
alias = "RechartsFunnelChart"
- # The source data, in which each element is an object.
- data: Var[List[Dict[str, Any]]]
+ # The layout of bars in the chart. Default: "centric"
+ layout: Var[str]
- # If any two categorical charts(rx.line_chart, rx.area_chart, rx.bar_chart, rx.composed_chart) have the same sync_id, these two charts can sync the position GraphingTooltip, and the start_index, end_index of Brush.
- sync_id: Var[str]
-
- # When sync_id is provided, allows customisation of how the charts will synchronize GraphingTooltips and brushes. Using 'index' (default setting), other charts will reuse current datum's index within the data array. In cases where data does not have the same length, this might yield unexpected results. In that case use 'value' which will try to match other charts values, or a fully custom function which will receive tick, data as argument and should return an index. 'index' | 'value' | function
- sync_method: Var[str]
-
- # The width of chart container. String or Integer
- width: Var[Union[str, int]] = "100%" # type: ignore
-
- # The height of chart container.
- height: Var[Union[str, int]] = "100%" # type: ignore
-
- # The layout of area in the chart. 'horizontal' | 'vertical'
- layout: Var[LiteralLayout]
-
- # The sizes of whitespace around the chart.
+ # The sizes of whitespace around the chart. Default: {"top": 5, "right": 5, "bottom": 5, "left": 5}
margin: Var[Dict[str, Any]]
- # The type of offset function used to generate the lower and upper values in the series array. The four types are built-in offsets in d3-shape. 'expand' | 'none' | 'wiggle' | 'silhouette'
- stack_offset: Var[LiteralStackOffset]
-
- # The layout of bars in the chart. centeric
- layout: Var[str]
+ # The stroke color of each bar. String | Object
+ stroke: Var[Union[str, Color]]
# Valid children components
_valid_children: List[str] = ["Legend", "GraphingTooltip", "Funnel"]
- def get_event_triggers(self) -> dict[str, Union[Var, Any]]:
- """Get the event triggers that pass the component's value to the handler.
-
- Returns:
- A dict mapping the event trigger to the var that is passed to the handler.
- """
- return {
- EventTriggers.ON_CLICK: lambda: [],
- EventTriggers.ON_MOUSE_ENTER: lambda: [],
- EventTriggers.ON_MOUSE_MOVE: lambda: [],
- EventTriggers.ON_MOUSE_LEAVE: lambda: [],
- }
-
class Treemap(RechartsCharts):
"""A Treemap chart component in Recharts."""
@@ -478,33 +457,42 @@ class Treemap(RechartsCharts):
alias = "RechartsTreemap"
- # The width of chart container. String or Integer
+ # The width of chart container. String or Integer. Default: "100%"
width: Var[Union[str, int]] = "100%" # type: ignore
- # The height of chart container.
+ # The height of chart container. String or Integer. Default: "100%"
height: Var[Union[str, int]] = "100%" # type: ignore
# data of treemap. Array
data: Var[List[Dict[str, Any]]]
- # The key of a group of data which should be unique in a treemap. String | Number | Function
+ # The key of a group of data which should be unique in a treemap. String | Number. Default: "value"
data_key: Var[Union[str, int]]
+ # The key of each sector's name. String. Default: "name"
+ name_key: Var[str]
+
# The treemap will try to keep every single rectangle's aspect ratio near the aspectRatio given. Number
aspect_ratio: Var[int]
- # If set false, animation of area will be disabled.
+ # If set false, animation of area will be disabled. Default: True
is_animation_active: Var[bool]
- # Specifies when the animation should begin, the unit of this option is ms.
+ # Specifies when the animation should begin, the unit of this option is ms. Default: 0
animation_begin: Var[int]
- # Specifies the duration of animation, the unit of this option is ms.
+ # Specifies the duration of animation, the unit of this option is ms. Default: 1500
animation_duration: Var[int]
- # The type of easing function. 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'
+ # The type of easing function. 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'. Default: "ease"
animation_easing: Var[LiteralAnimationEasing]
+ # The customized event handler of animation start
+ on_animation_start: EventHandler[empty_event]
+
+ # The customized event handler of animation end
+ on_animation_end: EventHandler[empty_event]
+
@classmethod
def create(cls, *children, **props) -> Component:
"""Create a chart component.
@@ -521,3 +509,15 @@ class Treemap(RechartsCharts):
width=props.pop("width", "100%"),
height=props.pop("height", "100%"),
)
+
+
+area_chart = AreaChart.create
+bar_chart = BarChart.create
+line_chart = LineChart.create
+composed_chart = ComposedChart.create
+pie_chart = PieChart.create
+radar_chart = RadarChart.create
+radial_bar_chart = RadialBarChart.create
+scatter_chart = ScatterChart.create
+funnel_chart = FunnelChart.create
+treemap = Treemap.create
diff --git a/reflex/components/recharts/charts.pyi b/reflex/components/recharts/charts.pyi
index e8562ee4d..2c6d7fffa 100644
--- a/reflex/components/recharts/charts.pyi
+++ b/reflex/components/recharts/charts.pyi
@@ -1,85 +1,60 @@
"""Stub file for reflex/components/recharts/charts.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, List, Literal, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+from reflex.constants.colors import Color
+from reflex.event import EventType
from reflex.style import Style
-from typing import Any, Dict, List, Union
-from reflex.components.component import Component
-from reflex.components.recharts.general import ResponsiveContainer
-from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.vars.base import Var
+
from .recharts import (
- LiteralAnimationEasing,
- LiteralComposedChartBaseValue,
- LiteralLayout,
- LiteralStackOffset,
- LiteralSyncMethod,
RechartsCharts,
)
class ChartBase(RechartsCharts):
- def get_event_triggers(self) -> dict[str, Union[Var, Any]]: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- data: Optional[Union[Var[List[Dict[str, Any]]], List[Dict[str, Any]]]] = None,
- sync_id: Optional[Union[Var[str], str]] = None,
- sync_method: Optional[
- Union[Var[Literal["index", "value"]], Literal["index", "value"]]
- ] = None,
- width: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- height: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- layout: Optional[
- Union[
- Var[Literal["horizontal", "vertical"]],
- Literal["horizontal", "vertical"],
- ]
- ] = None,
- margin: Optional[Union[Var[Dict[str, Any]], Dict[str, Any]]] = None,
- stack_offset: Optional[
- Union[
- Var[Literal["expand", "none", "wiggle", "silhouette"]],
- Literal["expand", "none", "wiggle", "silhouette"],
- ]
- ] = None,
+ width: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ height: Optional[Union[Var[Union[int, str]], int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ChartBase":
"""Create a chart component.
Args:
*children: The children of the chart component.
- data: The source data, in which each element is an object.
- sync_id: If any two categorical charts(rx.line_chart, rx.area_chart, rx.bar_chart, rx.composed_chart) have the same sync_id, these two charts can sync the position GraphingTooltip, and the start_index, end_index of Brush.
- sync_method: When sync_id is provided, allows customisation of how the charts will synchronize GraphingTooltips and brushes. Using 'index' (default setting), other charts will reuse current datum's index within the data array. In cases where data does not have the same length, this might yield unexpected results. In that case use 'value' which will try to match other charts values, or a fully custom function which will receive tick, data as argument and should return an index. 'index' | 'value' | function
width: The width of chart container. String or Integer
height: The height of chart container.
- layout: The layout of area in the chart. 'horizontal' | 'vertical'
- margin: The sizes of whitespace around the chart.
- stack_offset: The type of offset function used to generate the lower and upper values in the series array. The four types are built-in offsets in d3-shape. 'expand' | 'none' | 'wiggle' | 'silhouette'
+ on_click: The customized event handler of click on the component in this chart
+ on_mouse_enter: The customized event handler of mouseenter on the component in this chart
+ on_mouse_move: The customized event handler of mousemove on the component in this chart
+ on_mouse_leave: The customized event handler of mouseleave on the component in this chart
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -93,7 +68,85 @@ class ChartBase(RechartsCharts):
"""
...
-class AreaChart(ChartBase):
+class CategoricalChartBase(ChartBase):
+ @overload
+ @classmethod
+ def create( # type: ignore
+ cls,
+ *children,
+ data: Optional[Union[List[Dict[str, Any]], Var[List[Dict[str, Any]]]]] = None,
+ margin: Optional[Union[Dict[str, Any], Var[Dict[str, Any]]]] = None,
+ sync_id: Optional[Union[Var[str], str]] = None,
+ sync_method: Optional[
+ Union[Literal["index", "value"], Var[Literal["index", "value"]]]
+ ] = None,
+ layout: Optional[
+ Union[
+ Literal["horizontal", "vertical"],
+ Var[Literal["horizontal", "vertical"]],
+ ]
+ ] = None,
+ stack_offset: Optional[
+ Union[
+ Literal["expand", "none", "silhouette", "wiggle"],
+ Var[Literal["expand", "none", "silhouette", "wiggle"]],
+ ]
+ ] = None,
+ width: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ height: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ style: Optional[Style] = None,
+ key: Optional[Any] = None,
+ id: Optional[Any] = None,
+ class_name: Optional[Any] = None,
+ autofocus: Optional[bool] = None,
+ custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
+ ) -> "CategoricalChartBase":
+ """Create a chart component.
+
+ Args:
+ *children: The children of the chart component.
+ data: The source data, in which each element is an object.
+ margin: The sizes of whitespace around the chart, i.e. {"top": 50, "right": 30, "left": 20, "bottom": 5}.
+ sync_id: If any two categorical charts(rx.line_chart, rx.area_chart, rx.bar_chart, rx.composed_chart) have the same sync_id, these two charts can sync the position GraphingTooltip, and the start_index, end_index of Brush.
+ sync_method: When sync_id is provided, allows customisation of how the charts will synchronize GraphingTooltips and brushes. Using 'index' (default setting), other charts will reuse current datum's index within the data array. In cases where data does not have the same length, this might yield unexpected results. In that case use 'value' which will try to match other charts values, or a fully custom function which will receive tick, data as argument and should return an index. 'index' | 'value' | function. Default: "index"
+ layout: The layout of area in the chart. 'horizontal' | 'vertical'. Default: "horizontal"
+ stack_offset: The type of offset function used to generate the lower and upper values in the series array. The four types are built-in offsets in d3-shape. 'expand' | 'none' | 'wiggle' | 'silhouette'
+ width: The width of chart container. String or Integer
+ height: The height of chart container.
+ on_click: The customized event handler of click on the component in this chart
+ on_mouse_enter: The customized event handler of mouseenter on the component in this chart
+ on_mouse_move: The customized event handler of mousemove on the component in this chart
+ on_mouse_leave: The customized event handler of mouseleave on the component in this chart
+ style: The style of the component.
+ key: A unique key for the component.
+ id: The id for the component.
+ class_name: The class name for the component.
+ autofocus: Whether the component should take the focus once the page is loaded
+ custom_attrs: custom attribute
+ **props: The properties of the chart component.
+
+ Returns:
+ The chart component wrapped in a responsive container.
+ """
+ ...
+
+class AreaChart(CategoricalChartBase):
@overload
@classmethod
def create( # type: ignore
@@ -101,63 +154,71 @@ class AreaChart(ChartBase):
*children,
base_value: Optional[
Union[
- Var[Union[int, Literal["dataMin", "dataMax", "auto"]]],
- Union[int, Literal["dataMin", "dataMax", "auto"]],
+ Literal["auto", "dataMax", "dataMin"],
+ Var[Union[Literal["auto", "dataMax", "dataMin"], int]],
+ int,
+ ]
+ ] = None,
+ data: Optional[Union[List[Dict[str, Any]], Var[List[Dict[str, Any]]]]] = None,
+ margin: Optional[Union[Dict[str, Any], Var[Dict[str, Any]]]] = None,
+ sync_id: Optional[Union[Var[str], str]] = None,
+ sync_method: Optional[
+ Union[Literal["index", "value"], Var[Literal["index", "value"]]]
+ ] = None,
+ layout: Optional[
+ Union[
+ Literal["horizontal", "vertical"],
+ Var[Literal["horizontal", "vertical"]],
]
] = None,
stack_offset: Optional[
Union[
- Var[Literal["expand", "none", "wiggle", "silhouette"]],
- Literal["expand", "none", "wiggle", "silhouette"],
+ Literal["expand", "none", "silhouette", "wiggle"],
+ Var[Literal["expand", "none", "silhouette", "wiggle"]],
]
] = None,
- data: Optional[Union[Var[List[Dict[str, Any]]], List[Dict[str, Any]]]] = None,
- sync_id: Optional[Union[Var[str], str]] = None,
- sync_method: Optional[
- Union[Var[Literal["index", "value"]], Literal["index", "value"]]
- ] = None,
- width: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- height: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- layout: Optional[
- Union[
- Var[Literal["horizontal", "vertical"]],
- Literal["horizontal", "vertical"],
- ]
- ] = None,
- margin: Optional[Union[Var[Dict[str, Any]], Dict[str, Any]]] = None,
+ width: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ height: Optional[Union[Var[Union[int, str]], int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "AreaChart":
"""Create a chart component.
Args:
*children: The children of the chart component.
- base_value: The base value of area. Number | 'dataMin' | 'dataMax' | 'auto'
- stack_offset: The type of offset function used to generate the lower and upper values in the series array. The four types are built-in offsets in d3-shape. 'expand' | 'none' | 'wiggle' | 'silhouette'
+ base_value: The base value of area. Number | 'dataMin' | 'dataMax' | 'auto'. Default: "auto"
data: The source data, in which each element is an object.
+ margin: The sizes of whitespace around the chart, i.e. {"top": 50, "right": 30, "left": 20, "bottom": 5}.
sync_id: If any two categorical charts(rx.line_chart, rx.area_chart, rx.bar_chart, rx.composed_chart) have the same sync_id, these two charts can sync the position GraphingTooltip, and the start_index, end_index of Brush.
- sync_method: When sync_id is provided, allows customisation of how the charts will synchronize GraphingTooltips and brushes. Using 'index' (default setting), other charts will reuse current datum's index within the data array. In cases where data does not have the same length, this might yield unexpected results. In that case use 'value' which will try to match other charts values, or a fully custom function which will receive tick, data as argument and should return an index. 'index' | 'value' | function
+ sync_method: When sync_id is provided, allows customisation of how the charts will synchronize GraphingTooltips and brushes. Using 'index' (default setting), other charts will reuse current datum's index within the data array. In cases where data does not have the same length, this might yield unexpected results. In that case use 'value' which will try to match other charts values, or a fully custom function which will receive tick, data as argument and should return an index. 'index' | 'value' | function. Default: "index"
+ layout: The layout of area in the chart. 'horizontal' | 'vertical'. Default: "horizontal"
+ stack_offset: The type of offset function used to generate the lower and upper values in the series array. The four types are built-in offsets in d3-shape. 'expand' | 'none' | 'wiggle' | 'silhouette'
width: The width of chart container. String or Integer
height: The height of chart container.
- layout: The layout of area in the chart. 'horizontal' | 'vertical'
- margin: The sizes of whitespace around the chart.
+ on_click: The customized event handler of click on the component in this chart
+ on_mouse_enter: The customized event handler of mouseenter on the component in this chart
+ on_mouse_move: The customized event handler of mousemove on the component in this chart
+ on_mouse_leave: The customized event handler of mouseleave on the component in this chart
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -171,74 +232,81 @@ class AreaChart(ChartBase):
"""
...
-class BarChart(ChartBase):
+class BarChart(CategoricalChartBase):
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- bar_category_gap: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- bar_gap: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
+ bar_category_gap: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ bar_gap: Optional[Union[Var[Union[int, str]], int, str]] = None,
bar_size: Optional[Union[Var[int], int]] = None,
max_bar_size: Optional[Union[Var[int], int]] = None,
stack_offset: Optional[
Union[
- Var[Literal["expand", "none", "wiggle", "silhouette"]],
- Literal["expand", "none", "wiggle", "silhouette"],
+ Literal["expand", "none", "silhouette", "wiggle"],
+ Var[Literal["expand", "none", "silhouette", "wiggle"]],
]
] = None,
reverse_stack_order: Optional[Union[Var[bool], bool]] = None,
- data: Optional[Union[Var[List[Dict[str, Any]]], List[Dict[str, Any]]]] = None,
+ data: Optional[Union[List[Dict[str, Any]], Var[List[Dict[str, Any]]]]] = None,
+ margin: Optional[Union[Dict[str, Any], Var[Dict[str, Any]]]] = None,
sync_id: Optional[Union[Var[str], str]] = None,
sync_method: Optional[
- Union[Var[Literal["index", "value"]], Literal["index", "value"]]
+ Union[Literal["index", "value"], Var[Literal["index", "value"]]]
] = None,
- width: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- height: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
layout: Optional[
Union[
- Var[Literal["horizontal", "vertical"]],
Literal["horizontal", "vertical"],
+ Var[Literal["horizontal", "vertical"]],
]
] = None,
- margin: Optional[Union[Var[Dict[str, Any]], Dict[str, Any]]] = None,
+ width: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ height: Optional[Union[Var[Union[int, str]], int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "BarChart":
"""Create a chart component.
Args:
*children: The children of the chart component.
- bar_category_gap: The gap between two bar categories, which can be a percent value or a fixed value. Percentage | Number
- bar_gap: The gap between two bars in the same category, which can be a percent value or a fixed value. Percentage | Number
+ bar_category_gap: The gap between two bar categories, which can be a percent value or a fixed value. Percentage | Number. Default: "10%"
+ bar_gap: The gap between two bars in the same category, which can be a percent value or a fixed value. Percentage | Number. Default: 4
bar_size: The width of all the bars in the chart. Number
max_bar_size: The maximum width of all the bars in a horizontal BarChart, or maximum height in a vertical BarChart.
stack_offset: The type of offset function used to generate the lower and upper values in the series array. The four types are built-in offsets in d3-shape. 'expand' | 'none' | 'wiggle' | 'silhouette'
- reverse_stack_order: If false set, stacked items will be rendered left to right. If true set, stacked items will be rendered right to left. (Render direction affects SVG layering, not x position.)
+ reverse_stack_order: If false set, stacked items will be rendered left to right. If true set, stacked items will be rendered right to left. (Render direction affects SVG layering, not x position.) Default: False
data: The source data, in which each element is an object.
+ margin: The sizes of whitespace around the chart, i.e. {"top": 50, "right": 30, "left": 20, "bottom": 5}.
sync_id: If any two categorical charts(rx.line_chart, rx.area_chart, rx.bar_chart, rx.composed_chart) have the same sync_id, these two charts can sync the position GraphingTooltip, and the start_index, end_index of Brush.
- sync_method: When sync_id is provided, allows customisation of how the charts will synchronize GraphingTooltips and brushes. Using 'index' (default setting), other charts will reuse current datum's index within the data array. In cases where data does not have the same length, this might yield unexpected results. In that case use 'value' which will try to match other charts values, or a fully custom function which will receive tick, data as argument and should return an index. 'index' | 'value' | function
+ sync_method: When sync_id is provided, allows customisation of how the charts will synchronize GraphingTooltips and brushes. Using 'index' (default setting), other charts will reuse current datum's index within the data array. In cases where data does not have the same length, this might yield unexpected results. In that case use 'value' which will try to match other charts values, or a fully custom function which will receive tick, data as argument and should return an index. 'index' | 'value' | function. Default: "index"
+ layout: The layout of area in the chart. 'horizontal' | 'vertical'. Default: "horizontal"
width: The width of chart container. String or Integer
height: The height of chart container.
- layout: The layout of area in the chart. 'horizontal' | 'vertical'
- margin: The sizes of whitespace around the chart.
+ on_click: The customized event handler of click on the component in this chart
+ on_mouse_enter: The customized event handler of mouseenter on the component in this chart
+ on_mouse_move: The customized event handler of mousemove on the component in this chart
+ on_mouse_leave: The customized event handler of mouseleave on the component in this chart
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -252,64 +320,71 @@ class BarChart(ChartBase):
"""
...
-class LineChart(ChartBase):
+class LineChart(CategoricalChartBase):
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- data: Optional[Union[Var[List[Dict[str, Any]]], List[Dict[str, Any]]]] = None,
+ data: Optional[Union[List[Dict[str, Any]], Var[List[Dict[str, Any]]]]] = None,
+ margin: Optional[Union[Dict[str, Any], Var[Dict[str, Any]]]] = None,
sync_id: Optional[Union[Var[str], str]] = None,
sync_method: Optional[
- Union[Var[Literal["index", "value"]], Literal["index", "value"]]
+ Union[Literal["index", "value"], Var[Literal["index", "value"]]]
] = None,
- width: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- height: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
layout: Optional[
Union[
- Var[Literal["horizontal", "vertical"]],
Literal["horizontal", "vertical"],
+ Var[Literal["horizontal", "vertical"]],
]
] = None,
- margin: Optional[Union[Var[Dict[str, Any]], Dict[str, Any]]] = None,
stack_offset: Optional[
Union[
- Var[Literal["expand", "none", "wiggle", "silhouette"]],
- Literal["expand", "none", "wiggle", "silhouette"],
+ Literal["expand", "none", "silhouette", "wiggle"],
+ Var[Literal["expand", "none", "silhouette", "wiggle"]],
]
] = None,
+ width: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ height: Optional[Union[Var[Union[int, str]], int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "LineChart":
"""Create a chart component.
Args:
*children: The children of the chart component.
data: The source data, in which each element is an object.
+ margin: The sizes of whitespace around the chart, i.e. {"top": 50, "right": 30, "left": 20, "bottom": 5}.
sync_id: If any two categorical charts(rx.line_chart, rx.area_chart, rx.bar_chart, rx.composed_chart) have the same sync_id, these two charts can sync the position GraphingTooltip, and the start_index, end_index of Brush.
- sync_method: When sync_id is provided, allows customisation of how the charts will synchronize GraphingTooltips and brushes. Using 'index' (default setting), other charts will reuse current datum's index within the data array. In cases where data does not have the same length, this might yield unexpected results. In that case use 'value' which will try to match other charts values, or a fully custom function which will receive tick, data as argument and should return an index. 'index' | 'value' | function
+ sync_method: When sync_id is provided, allows customisation of how the charts will synchronize GraphingTooltips and brushes. Using 'index' (default setting), other charts will reuse current datum's index within the data array. In cases where data does not have the same length, this might yield unexpected results. In that case use 'value' which will try to match other charts values, or a fully custom function which will receive tick, data as argument and should return an index. 'index' | 'value' | function. Default: "index"
+ layout: The layout of area in the chart. 'horizontal' | 'vertical'. Default: "horizontal"
+ stack_offset: The type of offset function used to generate the lower and upper values in the series array. The four types are built-in offsets in d3-shape. 'expand' | 'none' | 'wiggle' | 'silhouette'
width: The width of chart container. String or Integer
height: The height of chart container.
- layout: The layout of area in the chart. 'horizontal' | 'vertical'
- margin: The sizes of whitespace around the chart.
- stack_offset: The type of offset function used to generate the lower and upper values in the series array. The four types are built-in offsets in d3-shape. 'expand' | 'none' | 'wiggle' | 'silhouette'
+ on_click: The customized event handler of click on the component in this chart
+ on_mouse_enter: The customized event handler of mouseenter on the component in this chart
+ on_mouse_move: The customized event handler of mousemove on the component in this chart
+ on_mouse_leave: The customized event handler of mouseleave on the component in this chart
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -323,7 +398,7 @@ class LineChart(ChartBase):
"""
...
-class ComposedChart(ChartBase):
+class ComposedChart(CategoricalChartBase):
@overload
@classmethod
def create( # type: ignore
@@ -331,71 +406,79 @@ class ComposedChart(ChartBase):
*children,
base_value: Optional[
Union[
- Var[Union[int, Literal["dataMin", "dataMax", "auto"]]],
- Union[int, Literal["dataMin", "dataMax", "auto"]],
+ Literal["auto", "dataMax", "dataMin"],
+ Var[Union[Literal["auto", "dataMax", "dataMin"], int]],
+ int,
]
] = None,
- bar_category_gap: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
+ bar_category_gap: Optional[Union[Var[Union[int, str]], int, str]] = None,
bar_gap: Optional[Union[Var[int], int]] = None,
bar_size: Optional[Union[Var[int], int]] = None,
reverse_stack_order: Optional[Union[Var[bool], bool]] = None,
- data: Optional[Union[Var[List[Dict[str, Any]]], List[Dict[str, Any]]]] = None,
+ data: Optional[Union[List[Dict[str, Any]], Var[List[Dict[str, Any]]]]] = None,
+ margin: Optional[Union[Dict[str, Any], Var[Dict[str, Any]]]] = None,
sync_id: Optional[Union[Var[str], str]] = None,
sync_method: Optional[
- Union[Var[Literal["index", "value"]], Literal["index", "value"]]
+ Union[Literal["index", "value"], Var[Literal["index", "value"]]]
] = None,
- width: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- height: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
layout: Optional[
Union[
- Var[Literal["horizontal", "vertical"]],
Literal["horizontal", "vertical"],
+ Var[Literal["horizontal", "vertical"]],
]
] = None,
- margin: Optional[Union[Var[Dict[str, Any]], Dict[str, Any]]] = None,
stack_offset: Optional[
Union[
- Var[Literal["expand", "none", "wiggle", "silhouette"]],
- Literal["expand", "none", "wiggle", "silhouette"],
+ Literal["expand", "none", "silhouette", "wiggle"],
+ Var[Literal["expand", "none", "silhouette", "wiggle"]],
]
] = None,
+ width: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ height: Optional[Union[Var[Union[int, str]], int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ComposedChart":
"""Create a chart component.
Args:
*children: The children of the chart component.
- base_value: The base value of area. Number | 'dataMin' | 'dataMax' | 'auto'
- bar_category_gap: The gap between two bar categories, which can be a percent value or a fixed value. Percentage | Number
- bar_gap: The gap between two bars in the same category, which can be a percent value or a fixed value. Percentage | Number
- bar_size: The width of all the bars in the chart. Number
- reverse_stack_order: If false set, stacked items will be rendered left to right. If true set, stacked items will be rendered right to left. (Render direction affects SVG layering, not x position.)
+ base_value: The base value of area. Number | 'dataMin' | 'dataMax' | 'auto'. Default: "auto"
+ bar_category_gap: The gap between two bar categories, which can be a percent value or a fixed value. Percentage | Number. Default: "10%"
+ bar_gap: The gap between two bars in the same category. Default: 4
+ bar_size: The width or height of each bar. If the barSize is not specified, the size of the bar will be calculated by the barCategoryGap, barGap and the quantity of bar groups.
+ reverse_stack_order: If false set, stacked items will be rendered left to right. If true set, stacked items will be rendered right to left. (Render direction affects SVG layering, not x position). Default: False
data: The source data, in which each element is an object.
+ margin: The sizes of whitespace around the chart, i.e. {"top": 50, "right": 30, "left": 20, "bottom": 5}.
sync_id: If any two categorical charts(rx.line_chart, rx.area_chart, rx.bar_chart, rx.composed_chart) have the same sync_id, these two charts can sync the position GraphingTooltip, and the start_index, end_index of Brush.
- sync_method: When sync_id is provided, allows customisation of how the charts will synchronize GraphingTooltips and brushes. Using 'index' (default setting), other charts will reuse current datum's index within the data array. In cases where data does not have the same length, this might yield unexpected results. In that case use 'value' which will try to match other charts values, or a fully custom function which will receive tick, data as argument and should return an index. 'index' | 'value' | function
+ sync_method: When sync_id is provided, allows customisation of how the charts will synchronize GraphingTooltips and brushes. Using 'index' (default setting), other charts will reuse current datum's index within the data array. In cases where data does not have the same length, this might yield unexpected results. In that case use 'value' which will try to match other charts values, or a fully custom function which will receive tick, data as argument and should return an index. 'index' | 'value' | function. Default: "index"
+ layout: The layout of area in the chart. 'horizontal' | 'vertical'. Default: "horizontal"
+ stack_offset: The type of offset function used to generate the lower and upper values in the series array. The four types are built-in offsets in d3-shape. 'expand' | 'none' | 'wiggle' | 'silhouette'
width: The width of chart container. String or Integer
height: The height of chart container.
- layout: The layout of area in the chart. 'horizontal' | 'vertical'
- margin: The sizes of whitespace around the chart.
- stack_offset: The type of offset function used to generate the lower and upper values in the series array. The four types are built-in offsets in d3-shape. 'expand' | 'none' | 'wiggle' | 'silhouette'
+ on_click: The customized event handler of click on the component in this chart
+ on_mouse_enter: The customized event handler of mouseenter on the component in this chart
+ on_mouse_move: The customized event handler of mousemove on the component in this chart
+ on_mouse_leave: The customized event handler of mouseleave on the component in this chart
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -410,61 +493,52 @@ class ComposedChart(ChartBase):
...
class PieChart(ChartBase):
- def get_event_triggers(self) -> dict[str, Union[Var, Any]]: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- data: Optional[Union[Var[List[Dict[str, Any]]], List[Dict[str, Any]]]] = None,
- sync_id: Optional[Union[Var[str], str]] = None,
- sync_method: Optional[
- Union[Var[Literal["index", "value"]], Literal["index", "value"]]
- ] = None,
- width: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- height: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- layout: Optional[
- Union[
- Var[Literal["horizontal", "vertical"]],
- Literal["horizontal", "vertical"],
- ]
- ] = None,
- margin: Optional[Union[Var[Dict[str, Any]], Dict[str, Any]]] = None,
- stack_offset: Optional[
- Union[
- Var[Literal["expand", "none", "wiggle", "silhouette"]],
- Literal["expand", "none", "wiggle", "silhouette"],
- ]
- ] = None,
+ margin: Optional[Union[Dict[str, Any], Var[Dict[str, Any]]]] = None,
+ width: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ height: Optional[Union[Var[Union[int, str]], int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "PieChart":
"""Create a chart component.
Args:
*children: The children of the chart component.
- data: The source data, in which each element is an object.
- sync_id: If any two categorical charts(rx.line_chart, rx.area_chart, rx.bar_chart, rx.composed_chart) have the same sync_id, these two charts can sync the position GraphingTooltip, and the start_index, end_index of Brush.
- sync_method: When sync_id is provided, allows customisation of how the charts will synchronize GraphingTooltips and brushes. Using 'index' (default setting), other charts will reuse current datum's index within the data array. In cases where data does not have the same length, this might yield unexpected results. In that case use 'value' which will try to match other charts values, or a fully custom function which will receive tick, data as argument and should return an index. 'index' | 'value' | function
+ margin: The sizes of whitespace around the chart, i.e. {"top": 50, "right": 30, "left": 20, "bottom": 5}.
+ on_mouse_down: The customized event handler of mousedown on the sectors in this group
+ on_mouse_up: The customized event handler of mouseup on the sectors in this group
+ on_mouse_over: The customized event handler of mouseover on the sectors in this group
+ on_mouse_out: The customized event handler of mouseout on the sectors in this group
width: The width of chart container. String or Integer
height: The height of chart container.
- layout: The layout of area in the chart. 'horizontal' | 'vertical'
- margin: The sizes of whitespace around the chart.
- stack_offset: The type of offset function used to generate the lower and upper values in the series array. The four types are built-in offsets in d3-shape. 'expand' | 'none' | 'wiggle' | 'silhouette'
+ on_click: The customized event handler of click on the component in this chart
+ on_mouse_enter: The customized event handler of mouseenter on the component in this chart
+ on_mouse_move: The customized event handler of mousemove on the component in this chart
+ on_mouse_leave: The customized event handler of mouseleave on the component in this chart
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -485,70 +559,44 @@ class RadarChart(ChartBase):
def create( # type: ignore
cls,
*children,
- cx: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- cy: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
+ data: Optional[Union[List[Dict[str, Any]], Var[List[Dict[str, Any]]]]] = None,
+ margin: Optional[Union[Dict[str, Any], Var[Dict[str, Any]]]] = None,
+ cx: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ cy: Optional[Union[Var[Union[int, str]], int, str]] = None,
start_angle: Optional[Union[Var[int], int]] = None,
end_angle: Optional[Union[Var[int], int]] = None,
- inner_radius: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- outer_radius: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- data: Optional[Union[Var[List[Dict[str, Any]]], List[Dict[str, Any]]]] = None,
- sync_id: Optional[Union[Var[str], str]] = None,
- sync_method: Optional[
- Union[Var[Literal["index", "value"]], Literal["index", "value"]]
- ] = None,
- width: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- height: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- layout: Optional[
- Union[
- Var[Literal["horizontal", "vertical"]],
- Literal["horizontal", "vertical"],
- ]
- ] = None,
- margin: Optional[Union[Var[Dict[str, Any]], Dict[str, Any]]] = None,
- stack_offset: Optional[
- Union[
- Var[Literal["expand", "none", "wiggle", "silhouette"]],
- Literal["expand", "none", "wiggle", "silhouette"],
- ]
- ] = None,
+ inner_radius: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ outer_radius: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ width: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ height: Optional[Union[Var[Union[int, str]], int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_click: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ **props,
) -> "RadarChart":
"""Create a chart component.
Args:
*children: The children of the chart component.
- cx: The The x-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of width. Number | Percentage
- cy: The The y-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of height. Number | Percentage
- start_angle: The angle of first radial direction line.
- end_angle: The angle of last point in the circle which should be startAngle - 360 or startAngle + 360. We'll calculate the direction of chart by 'startAngle' and 'endAngle'.
- inner_radius: The inner radius of first circle grid. If set a percentage, the final value is obtained by multiplying the percentage of maxRadius which is calculated by the width, height, cx, cy. Number | Percentage
- outer_radius: The outer radius of last circle grid. If set a percentage, the final value is obtained by multiplying the percentage of maxRadius which is calculated by the width, height, cx, cy. Number | Percentage
data: The source data, in which each element is an object.
- sync_id: If any two categorical charts(rx.line_chart, rx.area_chart, rx.bar_chart, rx.composed_chart) have the same sync_id, these two charts can sync the position GraphingTooltip, and the start_index, end_index of Brush.
- sync_method: When sync_id is provided, allows customisation of how the charts will synchronize GraphingTooltips and brushes. Using 'index' (default setting), other charts will reuse current datum's index within the data array. In cases where data does not have the same length, this might yield unexpected results. In that case use 'value' which will try to match other charts values, or a fully custom function which will receive tick, data as argument and should return an index. 'index' | 'value' | function
+ margin: The sizes of whitespace around the chart, i.e. {"top": 50, "right": 30, "left": 20, "bottom": 5}. Default: {"top": 0, "right": 0, "left": 0, "bottom": 0}
+ cx: The The x-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of width. Number | Percentage. Default: "50%"
+ cy: The The y-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of height. Number | Percentage. Default: "50%"
+ start_angle: The angle of first radial direction line. Default: 90
+ end_angle: The angle of last point in the circle which should be startAngle - 360 or startAngle + 360. We'll calculate the direction of chart by 'startAngle' and 'endAngle'. Default: -270
+ inner_radius: The inner radius of first circle grid. If set a percentage, the final value is obtained by multiplying the percentage of maxRadius which is calculated by the width, height, cx, cy. Number | Percentage. Default: 0
+ outer_radius: The outer radius of last circle grid. If set a percentage, the final value is obtained by multiplying the percentage of maxRadius which is calculated by the width, height, cx, cy. Number | Percentage. Default: "80%"
width: The width of chart container. String or Integer
height: The height of chart container.
- layout: The layout of area in the chart. 'horizontal' | 'vertical'
- margin: The sizes of whitespace around the chart.
- stack_offset: The type of offset function used to generate the lower and upper values in the series array. The four types are built-in offsets in d3-shape. 'expand' | 'none' | 'wiggle' | 'silhouette'
+ on_click: The customized event handler of click on the component in this chart
+ on_mouse_enter: The customized event handler of mouseenter on the component in this chart
+ on_mouse_leave: The customized event handler of mouseleave on the component in this chart
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -563,82 +611,68 @@ class RadarChart(ChartBase):
...
class RadialBarChart(ChartBase):
- def get_event_triggers(self) -> dict[str, Union[Var, Any]]: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- cx: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- cy: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
+ data: Optional[Union[List[Dict[str, Any]], Var[List[Dict[str, Any]]]]] = None,
+ margin: Optional[Union[Dict[str, Any], Var[Dict[str, Any]]]] = None,
+ cx: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ cy: Optional[Union[Var[Union[int, str]], int, str]] = None,
start_angle: Optional[Union[Var[int], int]] = None,
end_angle: Optional[Union[Var[int], int]] = None,
- inner_radius: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- outer_radius: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- bar_category_gap: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
+ inner_radius: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ outer_radius: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ bar_category_gap: Optional[Union[Var[Union[int, str]], int, str]] = None,
bar_gap: Optional[Union[Var[str], str]] = None,
bar_size: Optional[Union[Var[int], int]] = None,
- data: Optional[Union[Var[List[Dict[str, Any]]], List[Dict[str, Any]]]] = None,
- sync_id: Optional[Union[Var[str], str]] = None,
- sync_method: Optional[
- Union[Var[Literal["index", "value"]], Literal["index", "value"]]
- ] = None,
- width: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- height: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- layout: Optional[
- Union[
- Var[Literal["horizontal", "vertical"]],
- Literal["horizontal", "vertical"],
- ]
- ] = None,
- margin: Optional[Union[Var[Dict[str, Any]], Dict[str, Any]]] = None,
- stack_offset: Optional[
- Union[
- Var[Literal["expand", "none", "wiggle", "silhouette"]],
- Literal["expand", "none", "wiggle", "silhouette"],
- ]
- ] = None,
+ width: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ height: Optional[Union[Var[Union[int, str]], int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "RadialBarChart":
"""Create a chart component.
Args:
*children: The children of the chart component.
- cx: The The x-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of width. Number | Percentage
- cy: The The y-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of height. Number | Percentage
- start_angle: The angle of first radial direction line.
- end_angle: The angle of last point in the circle which should be startAngle - 360 or startAngle + 360. We'll calculate the direction of chart by 'startAngle' and 'endAngle'.
- inner_radius: The inner radius of first circle grid. If set a percentage, the final value is obtained by multiplying the percentage of maxRadius which is calculated by the width, height, cx, cy. Number | Percentage
- outer_radius: The outer radius of last circle grid. If set a percentage, the final value is obtained by multiplying the percentage of maxRadius which is calculated by the width, height, cx, cy. Number | Percentage
- bar_category_gap: The gap between two bar categories, which can be a percent value or a fixed value. Percentage | Number
- bar_gap: The gap between two bars in the same category, which can be a percent value or a fixed value. Percentage | Number
+ data: The source data which each element is an object.
+ margin: The sizes of whitespace around the chart. Default: {"top": 5, "right": 5, "left": 5 "bottom": 5}
+ cx: The The x-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of width. Number | Percentage. Default: "50%"
+ cy: The The y-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of height. Number | Percentage. Default: "50%"
+ start_angle: The angle of first radial direction line. Default: 0
+ end_angle: The angle of last point in the circle which should be startAngle - 360 or startAngle + 360. We'll calculate the direction of chart by 'startAngle' and 'endAngle'. Default: 360
+ inner_radius: The inner radius of first circle grid. If set a percentage, the final value is obtained by multiplying the percentage of maxRadius which is calculated by the width, height, cx, cy. Number | Percentage. Default: "30%"
+ outer_radius: The outer radius of last circle grid. If set a percentage, the final value is obtained by multiplying the percentage of maxRadius which is calculated by the width, height, cx, cy. Number | Percentage. Default: "100%"
+ bar_category_gap: The gap between two bar categories, which can be a percent value or a fixed value. Percentage | Number. Default: "10%"
+ bar_gap: The gap between two bars in the same category, which can be a percent value or a fixed value. Percentage | Number. Default: 4
bar_size: The size of each bar. If the barSize is not specified, the size of bar will be calculated by the barCategoryGap, barGap and the quantity of bar groups.
- data: The source data, in which each element is an object.
- sync_id: If any two categorical charts(rx.line_chart, rx.area_chart, rx.bar_chart, rx.composed_chart) have the same sync_id, these two charts can sync the position GraphingTooltip, and the start_index, end_index of Brush.
- sync_method: When sync_id is provided, allows customisation of how the charts will synchronize GraphingTooltips and brushes. Using 'index' (default setting), other charts will reuse current datum's index within the data array. In cases where data does not have the same length, this might yield unexpected results. In that case use 'value' which will try to match other charts values, or a fully custom function which will receive tick, data as argument and should return an index. 'index' | 'value' | function
width: The width of chart container. String or Integer
height: The height of chart container.
- layout: The layout of area in the chart. 'horizontal' | 'vertical'
- margin: The sizes of whitespace around the chart.
- stack_offset: The type of offset function used to generate the lower and upper values in the series array. The four types are built-in offsets in d3-shape. 'expand' | 'none' | 'wiggle' | 'silhouette'
+ on_click: The customized event handler of click on the component in this chart
+ on_mouse_enter: The customized event handler of mouseenter on the component in this chart
+ on_mouse_move: The customized event handler of mousemove on the component in this chart
+ on_mouse_leave: The customized event handler of mouseleave on the component in this chart
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -659,64 +693,36 @@ class ScatterChart(ChartBase):
def create( # type: ignore
cls,
*children,
- data: Optional[Union[Var[List[Dict[str, Any]]], List[Dict[str, Any]]]] = None,
- sync_id: Optional[Union[Var[str], str]] = None,
- sync_method: Optional[
- Union[Var[Literal["index", "value"]], Literal["index", "value"]]
- ] = None,
- width: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- height: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- layout: Optional[
- Union[
- Var[Literal["horizontal", "vertical"]],
- Literal["horizontal", "vertical"],
- ]
- ] = None,
- margin: Optional[Union[Var[Dict[str, Any]], Dict[str, Any]]] = None,
- stack_offset: Optional[
- Union[
- Var[Literal["expand", "none", "wiggle", "silhouette"]],
- Literal["expand", "none", "wiggle", "silhouette"],
- ]
- ] = None,
+ margin: Optional[Union[Dict[str, Any], Var[Dict[str, Any]]]] = None,
+ width: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ height: Optional[Union[Var[Union[int, str]], int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_click: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ **props,
) -> "ScatterChart":
"""Create a chart component.
Args:
*children: The children of the chart component.
- data: The source data, in which each element is an object.
- sync_id: If any two categorical charts(rx.line_chart, rx.area_chart, rx.bar_chart, rx.composed_chart) have the same sync_id, these two charts can sync the position GraphingTooltip, and the start_index, end_index of Brush.
- sync_method: When sync_id is provided, allows customisation of how the charts will synchronize GraphingTooltips and brushes. Using 'index' (default setting), other charts will reuse current datum's index within the data array. In cases where data does not have the same length, this might yield unexpected results. In that case use 'value' which will try to match other charts values, or a fully custom function which will receive tick, data as argument and should return an index. 'index' | 'value' | function
+ margin: The sizes of whitespace around the chart. Default: {"top": 5, "right": 5, "bottom": 5, "left": 5}
width: The width of chart container. String or Integer
height: The height of chart container.
- layout: The layout of area in the chart. 'horizontal' | 'vertical'
- margin: The sizes of whitespace around the chart.
- stack_offset: The type of offset function used to generate the lower and upper values in the series array. The four types are built-in offsets in d3-shape. 'expand' | 'none' | 'wiggle' | 'silhouette'
+ on_click: The customized event handler of click on the component in this chart
+ on_mouse_enter: The customized event handler of mouseenter on the component in this chart
+ on_mouse_move: The customized event handler of mousemove on the component in this chart
+ on_mouse_leave: The customized event handler of mouseleave on the component in this chart
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -730,68 +736,63 @@ class ScatterChart(ChartBase):
"""
...
-class FunnelChart(RechartsCharts):
- def get_event_triggers(self) -> dict[str, Union[Var, Any]]: ...
+class FunnelChart(ChartBase):
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- data: Optional[Union[Var[List[Dict[str, Any]]], List[Dict[str, Any]]]] = None,
- sync_id: Optional[Union[Var[str], str]] = None,
- sync_method: Optional[Union[Var[str], str]] = None,
- width: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- height: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
layout: Optional[Union[Var[str], str]] = None,
- margin: Optional[Union[Var[Dict[str, Any]], Dict[str, Any]]] = None,
- stack_offset: Optional[
- Union[
- Var[Literal["expand", "none", "wiggle", "silhouette"]],
- Literal["expand", "none", "wiggle", "silhouette"],
- ]
- ] = None,
+ margin: Optional[Union[Dict[str, Any], Var[Dict[str, Any]]]] = None,
+ stroke: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
+ width: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ height: Optional[Union[Var[Union[int, str]], int, str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "FunnelChart":
- """Create a new memoization leaf component.
+ """Create a chart component.
Args:
- *children: The children of the component.
- data: The source data, in which each element is an object.
- sync_id: If any two categorical charts(rx.line_chart, rx.area_chart, rx.bar_chart, rx.composed_chart) have the same sync_id, these two charts can sync the position GraphingTooltip, and the start_index, end_index of Brush.
- sync_method: When sync_id is provided, allows customisation of how the charts will synchronize GraphingTooltips and brushes. Using 'index' (default setting), other charts will reuse current datum's index within the data array. In cases where data does not have the same length, this might yield unexpected results. In that case use 'value' which will try to match other charts values, or a fully custom function which will receive tick, data as argument and should return an index. 'index' | 'value' | function
+ *children: The children of the chart component.
+ layout: The layout of bars in the chart. Default: "centric"
+ margin: The sizes of whitespace around the chart. Default: {"top": 5, "right": 5, "bottom": 5, "left": 5}
+ stroke: The stroke color of each bar. String | Object
width: The width of chart container. String or Integer
height: The height of chart container.
- layout: The layout of bars in the chart. centeric
- margin: The sizes of whitespace around the chart.
- stack_offset: The type of offset function used to generate the lower and upper values in the series array. The four types are built-in offsets in d3-shape. 'expand' | 'none' | 'wiggle' | 'silhouette'
+ on_click: The customized event handler of click on the component in this chart
+ on_mouse_enter: The customized event handler of mouseenter on the component in this chart
+ on_mouse_move: The customized event handler of mousemove on the component in this chart
+ on_mouse_leave: The customized event handler of mouseleave on the component in this chart
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
class_name: The class name for the component.
autofocus: Whether the component should take the focus once the page is loaded
custom_attrs: custom attribute
- **props: The props of the component.
+ **props: The properties of the chart component.
Returns:
- The memoization leaf
+ The chart component wrapped in a responsive container.
"""
...
@@ -801,18 +802,19 @@ class Treemap(RechartsCharts):
def create( # type: ignore
cls,
*children,
- width: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- height: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- data: Optional[Union[Var[List[Dict[str, Any]]], List[Dict[str, Any]]]] = None,
- data_key: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
+ width: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ height: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ data: Optional[Union[List[Dict[str, Any]], Var[List[Dict[str, Any]]]]] = None,
+ data_key: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ name_key: Optional[Union[Var[str], str]] = None,
aspect_ratio: Optional[Union[Var[int], int]] = None,
is_animation_active: Optional[Union[Var[bool], bool]] = None,
animation_begin: Optional[Union[Var[int], int]] = None,
animation_duration: Optional[Union[Var[int], int]] = None,
animation_easing: Optional[
Union[
- Var[Literal["ease", "ease-in", "ease-out", "ease-in-out", "linear"]],
- Literal["ease", "ease-in", "ease-out", "ease-in-out", "linear"],
+ Literal["ease", "ease-in", "ease-in-out", "ease-out", "linear"],
+ Var[Literal["ease", "ease-in", "ease-in-out", "ease-out", "linear"]],
]
] = None,
style: Optional[Style] = None,
@@ -821,66 +823,41 @@ class Treemap(RechartsCharts):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_animation_end: Optional[EventType[[]]] = None,
+ on_animation_start: Optional[EventType[[]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Treemap":
"""Create a chart component.
Args:
*children: The children of the chart component.
- width: The width of chart container. String or Integer
- height: The height of chart container.
+ width: The width of chart container. String or Integer. Default: "100%"
+ height: The height of chart container. String or Integer. Default: "100%"
data: data of treemap. Array
- data_key: The key of a group of data which should be unique in a treemap. String | Number | Function
+ data_key: The key of a group of data which should be unique in a treemap. String | Number. Default: "value"
+ name_key: The key of each sector's name. String. Default: "name"
aspect_ratio: The treemap will try to keep every single rectangle's aspect ratio near the aspectRatio given. Number
- is_animation_active: If set false, animation of area will be disabled.
- animation_begin: Specifies when the animation should begin, the unit of this option is ms.
- animation_duration: Specifies the duration of animation, the unit of this option is ms.
- animation_easing: The type of easing function. 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'
+ is_animation_active: If set false, animation of area will be disabled. Default: True
+ animation_begin: Specifies when the animation should begin, the unit of this option is ms. Default: 0
+ animation_duration: Specifies the duration of animation, the unit of this option is ms. Default: 1500
+ animation_easing: The type of easing function. 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'. Default: "ease"
+ on_animation_start: The customized event handler of animation start
+ on_animation_end: The customized event handler of animation end
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -893,3 +870,14 @@ class Treemap(RechartsCharts):
The Treemap component wrapped in a responsive container.
"""
...
+
+area_chart = AreaChart.create
+bar_chart = BarChart.create
+line_chart = LineChart.create
+composed_chart = ComposedChart.create
+pie_chart = PieChart.create
+radar_chart = RadarChart.create
+radial_bar_chart = RadialBarChart.create
+scatter_chart = ScatterChart.create
+funnel_chart = FunnelChart.create
+treemap = Treemap.create
diff --git a/reflex/components/recharts/general.py b/reflex/components/recharts/general.py
index ad23204d6..641e1562a 100644
--- a/reflex/components/recharts/general.py
+++ b/reflex/components/recharts/general.py
@@ -1,13 +1,16 @@
"""General components for Recharts."""
+
from __future__ import annotations
from typing import Any, Dict, List, Union
from reflex.components.component import MemoizationLeaf
-from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.constants.colors import Color
+from reflex.event import EventHandler, empty_event
+from reflex.vars.base import LiteralVar, Var
from .recharts import (
+ LiteralAnimationEasing,
LiteralIconType,
LiteralLayout,
LiteralLegendAlign,
@@ -27,21 +30,24 @@ class ResponsiveContainer(Recharts, MemoizationLeaf):
# The aspect ratio of the container. The final aspect ratio of the SVG element will be (width / height) * aspect. Number
aspect: Var[int]
- # The width of chart container. Can be a number or string
+ # The width of chart container. Can be a number or string. Default: "100%"
width: Var[Union[int, str]]
- # The height of chart container. Number
+ # The height of chart container. Can be a number or string. Default: "100%"
height: Var[Union[int, str]]
- # The minimum width of chart container.
+ # The minimum width of chart container. Number
min_width: Var[int]
# The minimum height of chart container. Number
min_height: Var[int]
- # If specified a positive number, debounced function will be used to handle the resize event.
+ # If specified a positive number, debounced function will be used to handle the resize event. Default: 0
debounce: Var[int]
+ # If specified provides a callback providing the updated chart width and height values.
+ on_resize: EventHandler[empty_event]
+
# Valid children components
_valid_children: List[str] = [
"AreaChart",
@@ -53,6 +59,7 @@ class ResponsiveContainer(Recharts, MemoizationLeaf):
"ScatterChart",
"Treemap",
"ComposedChart",
+ "FunnelChart",
]
@@ -69,21 +76,24 @@ class Legend(Recharts):
# The height of legend container. Number
height: Var[int]
- # The layout of legend items. 'horizontal' | 'vertical'
+ # The layout of legend items. 'horizontal' | 'vertical'. Default: "horizontal"
layout: Var[LiteralLayout]
- # The alignment of legend items in 'horizontal' direction, which can be 'left', 'center', 'right'.
+ # The alignment of legend items in 'horizontal' direction, which can be 'left', 'center', 'right'. Default: "center"
align: Var[LiteralLegendAlign]
- # The alignment of legend items in 'vertical' direction, which can be 'top', 'middle', 'bottom'.
+ # The alignment of legend items in 'vertical' direction, which can be 'top', 'middle', 'bottom'. Default: "bottom"
vertical_align: Var[LiteralVerticalAlign]
- # The size of icon in each legend item.
+ # The size of icon in each legend item. Default: 14
icon_size: Var[int]
# The type of icon in each legend item. 'line' | 'plainline' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye'
icon_type: Var[LiteralIconType]
+ # The source data of the content to be displayed in the legend, usually calculated internally. Default: []
+ payload: Var[List[Dict[str, Any]]]
+
# The width of chart container, usually calculated internally.
chart_width: Var[int]
@@ -93,20 +103,29 @@ class Legend(Recharts):
# The margin of chart container, usually calculated internally.
margin: Var[Dict[str, Any]]
- def get_event_triggers(self) -> dict[str, Union[Var, Any]]:
- """Get the event triggers that pass the component's value to the handler.
+ # The customized event handler of click on the items in this group
+ on_click: EventHandler[empty_event]
- Returns:
- A dict mapping the event trigger to the var that is passed to the handler.
- """
- return {
- EventTriggers.ON_CLICK: lambda: [],
- EventTriggers.ON_MOUSE_MOVE: lambda: [],
- EventTriggers.ON_MOUSE_OVER: lambda: [],
- EventTriggers.ON_MOUSE_OUT: lambda: [],
- EventTriggers.ON_MOUSE_ENTER: lambda: [],
- EventTriggers.ON_MOUSE_LEAVE: lambda: [],
- }
+ # The customized event handler of mousedown on the items in this group
+ on_mouse_down: EventHandler[empty_event]
+
+ # The customized event handler of mouseup on the items in this group
+ on_mouse_up: EventHandler[empty_event]
+
+ # The customized event handler of mousemove on the items in this group
+ on_mouse_move: EventHandler[empty_event]
+
+ # The customized event handler of mouseover on the items in this group
+ on_mouse_over: EventHandler[empty_event]
+
+ # The customized event handler of mouseout on the items in this group
+ on_mouse_out: EventHandler[empty_event]
+
+ # The customized event handler of mouseenter on the items in this group
+ on_mouse_enter: EventHandler[empty_event]
+
+ # The customized event handler of mouseleave on the items in this group
+ on_mouse_leave: EventHandler[empty_event]
class GraphingTooltip(Recharts):
@@ -126,11 +145,42 @@ class GraphingTooltip(Recharts):
filter_null: Var[bool]
# If set false, no cursor will be drawn when tooltip is active.
- cursor: Var[bool]
+ cursor: Var[Union[Dict[str, Any], bool]] = LiteralVar.create(
+ {
+ "strokeWidth": 1,
+ "fill": Color("gray", 3),
+ }
+ )
# The box of viewing area, which has the shape of {x: someVal, y: someVal, width: someVal, height: someVal}, usually calculated internally.
view_box: Var[Dict[str, Any]]
+ # The style of default tooltip content item which is a li element. DEFAULT: {}
+ item_style: Var[Dict[str, Any]] = LiteralVar.create(
+ {
+ "color": Color("gray", 12),
+ }
+ )
+
+ # The style of tooltip wrapper which is a dom element. DEFAULT: {}
+ wrapper_style: Var[Dict[str, Any]]
+ # The style of tooltip content which is a dom element. DEFAULT: {}
+ content_style: Var[Dict[str, Any]] = LiteralVar.create(
+ {
+ "background": Color("gray", 1),
+ "borderColor": Color("gray", 4),
+ "borderRadius": "8px",
+ }
+ )
+
+ # The style of default tooltip label which is a p element. DEFAULT: {}
+ label_style: Var[Dict[str, Any]] = LiteralVar.create({"color": Color("gray", 11)})
+
+ # This option allows the tooltip to extend beyond the viewBox of the chart itself. DEFAULT: { x: false, y: false }
+ allow_escape_view_box: Var[Dict[str, bool]] = LiteralVar.create(
+ {"x": False, "y": False}
+ )
+
# If set true, the tooltip is displayed. If set false, the tooltip is hidden, usually calculated internally.
active: Var[bool]
@@ -140,6 +190,15 @@ class GraphingTooltip(Recharts):
# The coordinate of tooltip which is usually calculated internally.
coordinate: Var[Dict[str, Any]]
+ # If set false, animation of tooltip will be disabled. DEFAULT: true in CSR, and false in SSR
+ is_animation_active: Var[bool]
+
+ # Specifies the duration of animation, the unit of this option is ms. DEFAULT: 1500
+ animation_duration: Var[int]
+
+ # The type of easing function. DEFAULT: 'ease'
+ animation_easing: Var[LiteralAnimationEasing]
+
class Label(Recharts):
"""A Label component in Recharts."""
@@ -171,14 +230,21 @@ class LabelList(Recharts):
# The key of a group of label values in data.
data_key: Var[Union[str, int]]
- # The position of each label relative to it view box。"Top" | "left" | "right" | "bottom" | "inside" | "outside" | "insideLeft" | "insideRight" | "insideTop" | "insideBottom" | "insideTopLeft" | "insideBottomLeft" | "insideTopRight" | "insideBottomRight" | "insideStart" | "insideEnd" | "end" | "center"
+ # The position of each label relative to it view box. "Top" | "left" | "right" | "bottom" | "inside" | "outside" | "insideLeft" | "insideRight" | "insideTop" | "insideBottom" | "insideTopLeft" | "insideBottomLeft" | "insideTopRight" | "insideBottomRight" | "insideStart" | "insideEnd" | "end" | "center"
position: Var[LiteralPosition]
- # The offset to the specified "position"
+ # The offset to the specified "position". Default: 5
offset: Var[int]
- # Color of the fill
- fill: Var[str]
+ # The fill color of each label. Default: rx.color("gray", 10)
+ fill: Var[Union[str, Color]] = LiteralVar.create(Color("gray", 10))
- # Color of the stroke
- stroke: Var[str]
+ # The stroke color of each label. Default: "none"
+ stroke: Var[Union[str, Color]] = LiteralVar.create("none")
+
+
+responsive_container = ResponsiveContainer.create
+legend = Legend.create
+graphing_tooltip = GraphingTooltip.create
+label = Label.create
+label_list = LabelList.create
diff --git a/reflex/components/recharts/general.pyi b/reflex/components/recharts/general.pyi
index 5b59acba6..affe362bb 100644
--- a/reflex/components/recharts/general.pyi
+++ b/reflex/components/recharts/general.pyi
@@ -1,22 +1,17 @@
"""Stub file for reflex/components/recharts/general.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, List, Literal, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Any, Dict, List, Union
from reflex.components.component import MemoizationLeaf
-from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.constants.colors import Color
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
+
from .recharts import (
- LiteralIconType,
- LiteralLayout,
- LiteralLegendAlign,
- LiteralPosition,
- LiteralVerticalAlign,
Recharts,
)
@@ -27,8 +22,8 @@ class ResponsiveContainer(Recharts, MemoizationLeaf):
cls,
*children,
aspect: Optional[Union[Var[int], int]] = None,
- width: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- height: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
+ width: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ height: Optional[Union[Var[Union[int, str]], int, str]] = None,
min_width: Optional[Union[Var[int], int]] = None,
min_height: Optional[Union[Var[int], int]] = None,
debounce: Optional[Union[Var[int], int]] = None,
@@ -38,63 +33,35 @@ class ResponsiveContainer(Recharts, MemoizationLeaf):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_resize: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "ResponsiveContainer":
"""Create a new memoization leaf component.
Args:
*children: The children of the component.
aspect: The aspect ratio of the container. The final aspect ratio of the SVG element will be (width / height) * aspect. Number
- width: The width of chart container. Can be a number or string
- height: The height of chart container. Number
- min_width: The minimum width of chart container.
+ width: The width of chart container. Can be a number or string. Default: "100%"
+ height: The height of chart container. Can be a number or string. Default: "100%"
+ min_width: The minimum width of chart container. Number
min_height: The minimum height of chart container. Number
- debounce: If specified a positive number, debounced function will be used to handle the resize event.
+ debounce: If specified a positive number, debounced function will be used to handle the resize event. Default: 0
+ on_resize: If specified provides a callback providing the updated chart width and height values.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -109,7 +76,6 @@ class ResponsiveContainer(Recharts, MemoizationLeaf):
...
class Legend(Recharts):
- def get_event_triggers(self) -> dict[str, Union[Var, Any]]: ...
@overload
@classmethod
def create( # type: ignore
@@ -119,81 +85,81 @@ class Legend(Recharts):
height: Optional[Union[Var[int], int]] = None,
layout: Optional[
Union[
- Var[Literal["horizontal", "vertical"]],
Literal["horizontal", "vertical"],
+ Var[Literal["horizontal", "vertical"]],
]
] = None,
align: Optional[
Union[
- Var[Literal["left", "center", "right"]],
- Literal["left", "center", "right"],
+ Literal["center", "left", "right"],
+ Var[Literal["center", "left", "right"]],
]
] = None,
vertical_align: Optional[
Union[
- Var[Literal["top", "middle", "bottom"]],
- Literal["top", "middle", "bottom"],
+ Literal["bottom", "middle", "top"],
+ Var[Literal["bottom", "middle", "top"]],
]
] = None,
icon_size: Optional[Union[Var[int], int]] = None,
icon_type: Optional[
Union[
+ Literal[
+ "circle",
+ "cross",
+ "diamond",
+ "line",
+ "plainline",
+ "rect",
+ "square",
+ "star",
+ "triangle",
+ "wye",
+ ],
Var[
Literal[
- "line",
- "plainline",
- "square",
- "rect",
"circle",
"cross",
"diamond",
+ "line",
+ "plainline",
+ "rect",
+ "square",
"star",
"triangle",
"wye",
]
],
- Literal[
- "line",
- "plainline",
- "square",
- "rect",
- "circle",
- "cross",
- "diamond",
- "star",
- "triangle",
- "wye",
- ],
]
] = None,
+ payload: Optional[
+ Union[List[Dict[str, Any]], Var[List[Dict[str, Any]]]]
+ ] = None,
chart_width: Optional[Union[Var[int], int]] = None,
chart_height: Optional[Union[Var[int], int]] = None,
- margin: Optional[Union[Var[Dict[str, Any]], Dict[str, Any]]] = None,
+ margin: Optional[Union[Dict[str, Any], Var[Dict[str, Any]]]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Legend":
"""Create the component.
@@ -201,14 +167,23 @@ class Legend(Recharts):
*children: The children of the component.
width: The width of legend container. Number
height: The height of legend container. Number
- layout: The layout of legend items. 'horizontal' | 'vertical'
- align: The alignment of legend items in 'horizontal' direction, which can be 'left', 'center', 'right'.
- vertical_align: The alignment of legend items in 'vertical' direction, which can be 'top', 'middle', 'bottom'.
- icon_size: The size of icon in each legend item.
+ layout: The layout of legend items. 'horizontal' | 'vertical'. Default: "horizontal"
+ align: The alignment of legend items in 'horizontal' direction, which can be 'left', 'center', 'right'. Default: "center"
+ vertical_align: The alignment of legend items in 'vertical' direction, which can be 'top', 'middle', 'bottom'. Default: "bottom"
+ icon_size: The size of icon in each legend item. Default: 14
icon_type: The type of icon in each legend item. 'line' | 'plainline' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye'
+ payload: The source data of the content to be displayed in the legend, usually calculated internally. Default: []
chart_width: The width of chart container, usually calculated internally.
chart_height: The height of chart container, usually calculated internally.
margin: The margin of chart container, usually calculated internally.
+ on_click: The customized event handler of click on the items in this group
+ on_mouse_down: The customized event handler of mousedown on the items in this group
+ on_mouse_up: The customized event handler of mouseup on the items in this group
+ on_mouse_move: The customized event handler of mousemove on the items in this group
+ on_mouse_over: The customized event handler of mouseover on the items in this group
+ on_mouse_out: The customized event handler of mouseout on the items in this group
+ on_mouse_enter: The customized event handler of mouseenter on the items in this group
+ on_mouse_leave: The customized event handler of mouseleave on the items in this group
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -231,63 +206,50 @@ class GraphingTooltip(Recharts):
separator: Optional[Union[Var[str], str]] = None,
offset: Optional[Union[Var[int], int]] = None,
filter_null: Optional[Union[Var[bool], bool]] = None,
- cursor: Optional[Union[Var[bool], bool]] = None,
- view_box: Optional[Union[Var[Dict[str, Any]], Dict[str, Any]]] = None,
+ cursor: Optional[
+ Union[Dict[str, Any], Var[Union[Dict[str, Any], bool]], bool]
+ ] = None,
+ view_box: Optional[Union[Dict[str, Any], Var[Dict[str, Any]]]] = None,
+ item_style: Optional[Union[Dict[str, Any], Var[Dict[str, Any]]]] = None,
+ wrapper_style: Optional[Union[Dict[str, Any], Var[Dict[str, Any]]]] = None,
+ content_style: Optional[Union[Dict[str, Any], Var[Dict[str, Any]]]] = None,
+ label_style: Optional[Union[Dict[str, Any], Var[Dict[str, Any]]]] = None,
+ allow_escape_view_box: Optional[
+ Union[Dict[str, bool], Var[Dict[str, bool]]]
+ ] = None,
active: Optional[Union[Var[bool], bool]] = None,
- position: Optional[Union[Var[Dict[str, Any]], Dict[str, Any]]] = None,
- coordinate: Optional[Union[Var[Dict[str, Any]], Dict[str, Any]]] = None,
+ position: Optional[Union[Dict[str, Any], Var[Dict[str, Any]]]] = None,
+ coordinate: Optional[Union[Dict[str, Any], Var[Dict[str, Any]]]] = None,
+ is_animation_active: Optional[Union[Var[bool], bool]] = None,
+ animation_duration: Optional[Union[Var[int], int]] = None,
+ animation_easing: Optional[
+ Union[
+ Literal["ease", "ease-in", "ease-in-out", "ease-out", "linear"],
+ Var[Literal["ease", "ease-in", "ease-in-out", "ease-out", "linear"]],
+ ]
+ ] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "GraphingTooltip":
"""Create the component.
@@ -298,9 +260,17 @@ class GraphingTooltip(Recharts):
filter_null: When an item of the payload has value null or undefined, this item won't be displayed.
cursor: If set false, no cursor will be drawn when tooltip is active.
view_box: The box of viewing area, which has the shape of {x: someVal, y: someVal, width: someVal, height: someVal}, usually calculated internally.
+ item_style: The style of default tooltip content item which is a li element. DEFAULT: {}
+ wrapper_style: The style of tooltip wrapper which is a dom element. DEFAULT: {}
+ content_style: The style of tooltip content which is a dom element. DEFAULT: {}
+ label_style: The style of default tooltip label which is a p element. DEFAULT: {}
+ allow_escape_view_box: This option allows the tooltip to extend beyond the viewBox of the chart itself. DEFAULT: { x: false, y: false }
active: If set true, the tooltip is displayed. If set false, the tooltip is hidden, usually calculated internally.
position: If this field is set, the tooltip position will be fixed and will not move anymore.
coordinate: The coordinate of tooltip which is usually calculated internally.
+ is_animation_active: If set false, animation of tooltip will be disabled. DEFAULT: true in CSR, and false in SSR
+ animation_duration: Specifies the duration of animation, the unit of this option is ms. DEFAULT: 1500
+ animation_easing: The type of easing function. DEFAULT: 'ease'
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -320,52 +290,52 @@ class Label(Recharts):
def create( # type: ignore
cls,
*children,
- view_box: Optional[Union[Var[Dict[str, Any]], Dict[str, Any]]] = None,
+ view_box: Optional[Union[Dict[str, Any], Var[Dict[str, Any]]]] = None,
value: Optional[Union[Var[str], str]] = None,
offset: Optional[Union[Var[int], int]] = None,
position: Optional[
Union[
- Var[
- Literal[
- "top",
- "left",
- "right",
- "bottom",
- "inside",
- "outside",
- "insideLeft",
- "insideRight",
- "insideTop",
- "insideBottom",
- "insideTopLeft",
- "insideBottomLeft",
- "insideTopRight",
- "insideBottomRight",
- "insideStart",
- "insideEnd",
- "end",
- "center",
- ]
- ],
Literal[
- "top",
- "left",
- "right",
"bottom",
+ "center",
+ "end",
"inside",
- "outside",
+ "insideBottom",
+ "insideBottomLeft",
+ "insideBottomRight",
+ "insideEnd",
"insideLeft",
"insideRight",
- "insideTop",
- "insideBottom",
- "insideTopLeft",
- "insideBottomLeft",
- "insideTopRight",
- "insideBottomRight",
"insideStart",
- "insideEnd",
- "end",
- "center",
+ "insideTop",
+ "insideTopLeft",
+ "insideTopRight",
+ "left",
+ "outside",
+ "right",
+ "top",
+ ],
+ Var[
+ Literal[
+ "bottom",
+ "center",
+ "end",
+ "inside",
+ "insideBottom",
+ "insideBottomLeft",
+ "insideBottomRight",
+ "insideEnd",
+ "insideLeft",
+ "insideRight",
+ "insideStart",
+ "insideTop",
+ "insideTopLeft",
+ "insideTopRight",
+ "left",
+ "outside",
+ "right",
+ "top",
+ ]
],
]
] = None,
@@ -375,52 +345,22 @@ class Label(Recharts):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Label":
"""Create the component.
@@ -449,118 +389,88 @@ class LabelList(Recharts):
def create( # type: ignore
cls,
*children,
- data_key: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
+ data_key: Optional[Union[Var[Union[int, str]], int, str]] = None,
position: Optional[
Union[
- Var[
- Literal[
- "top",
- "left",
- "right",
- "bottom",
- "inside",
- "outside",
- "insideLeft",
- "insideRight",
- "insideTop",
- "insideBottom",
- "insideTopLeft",
- "insideBottomLeft",
- "insideTopRight",
- "insideBottomRight",
- "insideStart",
- "insideEnd",
- "end",
- "center",
- ]
- ],
Literal[
- "top",
- "left",
- "right",
"bottom",
+ "center",
+ "end",
"inside",
- "outside",
+ "insideBottom",
+ "insideBottomLeft",
+ "insideBottomRight",
+ "insideEnd",
"insideLeft",
"insideRight",
- "insideTop",
- "insideBottom",
- "insideTopLeft",
- "insideBottomLeft",
- "insideTopRight",
- "insideBottomRight",
"insideStart",
- "insideEnd",
- "end",
- "center",
+ "insideTop",
+ "insideTopLeft",
+ "insideTopRight",
+ "left",
+ "outside",
+ "right",
+ "top",
+ ],
+ Var[
+ Literal[
+ "bottom",
+ "center",
+ "end",
+ "inside",
+ "insideBottom",
+ "insideBottomLeft",
+ "insideBottomRight",
+ "insideEnd",
+ "insideLeft",
+ "insideRight",
+ "insideStart",
+ "insideTop",
+ "insideTopLeft",
+ "insideTopRight",
+ "left",
+ "outside",
+ "right",
+ "top",
+ ]
],
]
] = None,
offset: Optional[Union[Var[int], int]] = None,
- fill: Optional[Union[Var[str], str]] = None,
- stroke: Optional[Union[Var[str], str]] = None,
+ fill: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
+ stroke: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "LabelList":
"""Create the component.
Args:
*children: The children of the component.
data_key: The key of a group of label values in data.
- position: The position of each label relative to it view box。"Top" | "left" | "right" | "bottom" | "inside" | "outside" | "insideLeft" | "insideRight" | "insideTop" | "insideBottom" | "insideTopLeft" | "insideBottomLeft" | "insideTopRight" | "insideBottomRight" | "insideStart" | "insideEnd" | "end" | "center"
- offset: The offset to the specified "position"
- fill: Color of the fill
- stroke: Color of the stroke
+ position: The position of each label relative to it view box. "Top" | "left" | "right" | "bottom" | "inside" | "outside" | "insideLeft" | "insideRight" | "insideTop" | "insideBottom" | "insideTopLeft" | "insideBottomLeft" | "insideTopRight" | "insideBottomRight" | "insideStart" | "insideEnd" | "end" | "center"
+ offset: The offset to the specified "position". Default: 5
+ fill: The fill color of each label. Default: rx.color("gray", 10)
+ stroke: The stroke color of each label. Default: "none"
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -573,3 +483,9 @@ class LabelList(Recharts):
The component.
"""
...
+
+responsive_container = ResponsiveContainer.create
+legend = Legend.create
+graphing_tooltip = GraphingTooltip.create
+label = Label.create
+label_list = LabelList.create
diff --git a/reflex/components/recharts/polar.py b/reflex/components/recharts/polar.py
index 256695740..ccb96f180 100644
--- a/reflex/components/recharts/polar.py
+++ b/reflex/components/recharts/polar.py
@@ -1,14 +1,19 @@
"""Polar charts in Recharts."""
+
from __future__ import annotations
from typing import Any, Dict, List, Union
from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.constants.colors import Color
+from reflex.event import EventHandler, empty_event
+from reflex.vars.base import LiteralVar, Var
from .recharts import (
LiteralAnimationEasing,
LiteralGridType,
+ LiteralLegendType,
+ LiteralOrientationLeftRightMiddle,
LiteralPolarRadiusType,
LiteralScale,
Recharts,
@@ -22,56 +27,74 @@ class Pie(Recharts):
alias = "RechartsPie"
- # data
+ # The source data which each element is an object.
data: Var[List[Dict[str, Any]]]
# The key of each sector's value.
data_key: Var[Union[str, int]]
- # The x-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of container width.
+ # The x-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of container width. Default: "50%"
cx: Var[Union[int, str]]
- # The y-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of container height.
+ # The y-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of container height. Default: "50%"
cy: Var[Union[int, str]]
- # The inner radius of pie, which can be set to a percent value.
+ # The inner radius of pie, which can be set to a percent value. Default: 0
inner_radius: Var[Union[int, str]]
- # The outer radius of pie, which can be set to a percent value.
+ # The outer radius of pie, which can be set to a percent value. Default: "80%"
outer_radius: Var[Union[int, str]]
- # The angle of first sector.
+ # The angle of first sector. Default: 0
start_angle: Var[int]
- # The direction of sectors. 1 means clockwise and -1 means anticlockwise.
+ # The end angle of last sector, which should be unequal to start_angle. Default: 360
end_angle: Var[int]
- # The minimum angle of each unzero data.
+ # The minimum angle of each unzero data. Default: 0
min_angle: Var[int]
- # The angle between two sectors.
+ # The angle between two sectors. Default: 0
padding_angle: Var[int]
- # The key of each sector's name.
+ # The key of each sector's name. Default: "name"
name_key: Var[str]
- # The type of icon in legend. If set to 'none', no legend item will be rendered.
- legend_type: Var[str]
+ # The type of icon in legend. If set to 'none', no legend item will be rendered. Default: "rect"
+ legend_type: Var[LiteralLegendType]
- # If false set, labels will not be drawn.
+ # If false set, labels will not be drawn. If true set, labels will be drawn which have the props calculated internally. Default: False
label: Var[bool] = False # type: ignore
- # If false set, label lines will not be drawn.
+ # If false set, label lines will not be drawn. If true set, label lines will be drawn which have the props calculated internally. Default: False
label_line: Var[bool]
+ # The index of active sector in Pie, this option can be changed in mouse event handlers.
+ data: Var[List[Dict[str, Any]]]
+
# Valid children components
_valid_children: List[str] = ["Cell", "LabelList"]
- # fill color
- fill: Var[str]
+ # Stoke color. Default: rx.color("accent", 9)
+ stroke: Var[Union[str, Color]] = LiteralVar.create(Color("accent", 9))
- # stroke color
- stroke: Var[str]
+ # Fill color. Default: rx.color("accent", 3)
+ fill: Var[Union[str, Color]] = LiteralVar.create(Color("accent", 3))
+
+ # If set false, animation of tooltip will be disabled. Default: true in CSR, and false in SSR
+ is_animation_active: Var[bool]
+
+ # Specifies when the animation should begin, the unit of this option is ms. Default: 400
+ animation_begin: Var[int]
+
+ # Specifies the duration of animation, the unit of this option is ms. Default: 1500
+ animation_duration: Var[int]
+
+ # The type of easing function. Default: "ease"
+ animation_easing: Var[LiteralAnimationEasing]
+
+ # The tabindex of wrapper surrounding the cells. Default: 0
+ root_tab_index: Var[int]
def get_event_triggers(self) -> dict[str, Union[Var, Any]]:
"""Get the event triggers that pass the component's value to the handler.
@@ -80,12 +103,14 @@ class Pie(Recharts):
A dict mapping the event trigger to the var that is passed to the handler.
"""
return {
- EventTriggers.ON_CLICK: lambda: [],
- EventTriggers.ON_MOUSE_MOVE: lambda: [],
- EventTriggers.ON_MOUSE_OVER: lambda: [],
- EventTriggers.ON_MOUSE_OUT: lambda: [],
- EventTriggers.ON_MOUSE_ENTER: lambda: [],
- EventTriggers.ON_MOUSE_LEAVE: lambda: [],
+ EventTriggers.ON_ANIMATION_START: empty_event,
+ EventTriggers.ON_ANIMATION_END: empty_event,
+ EventTriggers.ON_CLICK: empty_event,
+ EventTriggers.ON_MOUSE_MOVE: empty_event,
+ EventTriggers.ON_MOUSE_OVER: empty_event,
+ EventTriggers.ON_MOUSE_OUT: empty_event,
+ EventTriggers.ON_MOUSE_ENTER: empty_event,
+ EventTriggers.ON_MOUSE_LEAVE: empty_event,
}
@@ -102,36 +127,50 @@ class Radar(Recharts):
# The coordinates of all the vertexes of the radar shape, like [{ x, y }].
points: Var[List[Dict[str, Any]]]
- # If false set, dots will not be drawn
+ # If false set, dots will not be drawn. Default: True
dot: Var[bool]
- # Stoke color
- stroke: Var[str]
+ # Stoke color. Default: rx.color("accent", 9)
+ stroke: Var[Union[str, Color]] = LiteralVar.create(Color("accent", 9))
- # Fill color
- fill: Var[str]
+ # Fill color. Default: rx.color("accent", 3)
+ fill: Var[str] = LiteralVar.create(Color("accent", 3))
- # opacity
- fill_opacity: Var[float]
+ # opacity. Default: 0.6
+ fill_opacity: Var[float] = LiteralVar.create(0.6)
- # The type of icon in legend. If set to 'none', no legend item will be rendered.
- legend_type: Var[str]
+ # The type of icon in legend. If set to 'none', no legend item will be rendered. Default: "rect"
+ legend_type: Var[LiteralLegendType]
- # If false set, labels will not be drawn
+ # If false set, labels will not be drawn. Default: True
label: Var[bool]
- # Specifies when the animation should begin, the unit of this option is ms.
+ # If set false, animation of polygon will be disabled. Default: True in CSR, and False in SSR
+ is_animation_active: Var[bool]
+
+ # Specifies when the animation should begin, the unit of this option is ms. Default: 0
animation_begin: Var[int]
- # Specifies the duration of animation, the unit of this option is ms.
+ # Specifies the duration of animation, the unit of this option is ms. Default: 1500
animation_duration: Var[int]
- # The type of easing function. 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'
+ # The type of easing function. 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'. Default: "ease"
animation_easing: Var[LiteralAnimationEasing]
# Valid children components
_valid_children: List[str] = ["LabelList"]
+ def get_event_triggers(self) -> dict[str, Union[Var, Any]]:
+ """Get the event triggers that pass the component's value to the handler.
+
+ Returns:
+ A dict mapping the event trigger to the var that is passed to the handler.
+ """
+ return {
+ EventTriggers.ON_ANIMATION_START: empty_event,
+ EventTriggers.ON_ANIMATION_END: empty_event,
+ }
+
class RadialBar(Recharts):
"""A RadialBar chart component in Recharts."""
@@ -143,20 +182,35 @@ class RadialBar(Recharts):
# The source data which each element is an object.
data: Var[List[Dict[str, Any]]]
- # Min angle of each bar. A positive value between 0 and 360.
+ # The key of a group of data which should be unique to show the meaning of angle axis.
+ data_key: Var[Union[str, int]]
+
+ # Min angle of each bar. A positive value between 0 and 360. Default: 0
min_angle: Var[int]
- # Type of legend
- legend_type: Var[str]
+ # The type of icon in legend. If set to 'none', no legend item will be rendered. Default: "rect"
+ legend_type: Var[LiteralLegendType]
- # If false set, labels will not be drawn.
- label: Var[bool]
+ # If false set, labels will not be drawn. If true set, labels will be drawn which have the props calculated internally. Default: False
+ label: Var[Union[bool, Dict[str, Any]]]
- # If false set, background sector will not be drawn.
- background: Var[bool]
+ # If false set, background sector will not be drawn. Default: False
+ background: Var[Union[bool, Dict[str, Any]]]
+
+ # If set false, animation of radial bars will be disabled. Default: True
+ is_animation_active: Var[bool]
+
+ # Specifies when the animation should begin, the unit of this option is ms. Default: 0
+ animation_begin: Var[int]
+
+ # Specifies the duration of animation, the unit of this option is ms. Default 1500
+ animation_duration: Var[int]
+
+ # The type of easing function. 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'. Default: "ease"
+ animation_easing: Var[LiteralAnimationEasing]
# Valid children components
- _valid_children: List[str] = ["LabelList"]
+ _valid_children: List[str] = ["Cell", "LabelList"]
def get_event_triggers(self) -> dict[str, Union[Var, Any]]:
"""Get the event triggers that pass the component's value to the handler.
@@ -165,12 +219,14 @@ class RadialBar(Recharts):
A dict mapping the event trigger to the var that is passed to the handler.
"""
return {
- EventTriggers.ON_CLICK: lambda: [],
- EventTriggers.ON_MOUSE_MOVE: lambda: [],
- EventTriggers.ON_MOUSE_OVER: lambda: [],
- EventTriggers.ON_MOUSE_OUT: lambda: [],
- EventTriggers.ON_MOUSE_ENTER: lambda: [],
- EventTriggers.ON_MOUSE_LEAVE: lambda: [],
+ EventTriggers.ON_CLICK: empty_event,
+ EventTriggers.ON_MOUSE_MOVE: empty_event,
+ EventTriggers.ON_MOUSE_OVER: empty_event,
+ EventTriggers.ON_MOUSE_OUT: empty_event,
+ EventTriggers.ON_MOUSE_ENTER: empty_event,
+ EventTriggers.ON_MOUSE_LEAVE: empty_event,
+ EventTriggers.ON_ANIMATION_START: empty_event,
+ EventTriggers.ON_ANIMATION_END: empty_event,
}
@@ -193,44 +249,56 @@ class PolarAngleAxis(Recharts):
# The outer radius of circle grid. If set a percentage, the final value is obtained by multiplying the percentage of maxRadius which is calculated by the width, height, cx, cy.
radius: Var[Union[int, str]]
- # If false set, axis line will not be drawn. If true set, axis line will be drawn which have the props calculated internally. If object set, axis line will be drawn which have the props mergered by the internal calculated props and the option.
+ # If false set, axis line will not be drawn. If true set, axis line will be drawn which have the props calculated internally. If object set, axis line will be drawn which have the props mergered by the internal calculated props and the option. Default: True
axis_line: Var[Union[bool, Dict[str, Any]]]
- # The type of axis line.
- axis_line_type: Var[str]
+ # The type of axis line. Default: "polygon"
+ axis_line_type: Var[LiteralGridType]
- # If false set, tick lines will not be drawn. If true set, tick lines will be drawn which have the props calculated internally. If object set, tick lines will be drawn which have the props mergered by the internal calculated props and the option.
- tick_line: Var[Union[bool, Dict[str, Any]]]
+ # If false set, tick lines will not be drawn. If true set, tick lines will be drawn which have the props calculated internally. If object set, tick lines will be drawn which have the props mergered by the internal calculated props and the option. Default: False
+ tick_line: Var[Union[bool, Dict[str, Any]]] = LiteralVar.create(False)
- # The width or height of tick.
- tick: Var[Union[int, str]]
+ # If false set, ticks will not be drawn. If true set, ticks will be drawn which have the props calculated internally. If object set, ticks will be drawn which have the props mergered by the internal calculated props and the option. Default: True
+ tick: Var[Union[bool, Dict[str, Any]]]
# The array of every tick's value and angle.
ticks: Var[List[Dict[str, Any]]]
- # The orientation of axis text.
- orient: Var[str]
+ # The orientation of axis text. Default: "outer"
+ orientation: Var[str]
- # Allow the axis has duplicated categorys or not when the type of axis is "category".
+ # The stroke color of axis. Default: rx.color("gray", 10)
+ stroke: Var[Union[str, Color]] = LiteralVar.create(Color("gray", 10))
+
+ # Allow the axis has duplicated categorys or not when the type of axis is "category". Default: True
allow_duplicated_category: Var[bool]
- # Valid children components
+ # Valid children components.
_valid_children: List[str] = ["Label"]
- def get_event_triggers(self) -> dict[str, Union[Var, Any]]:
- """Get the event triggers that pass the component's value to the handler.
+ # The customized event handler of click on the ticks of this axis.
+ on_click: EventHandler[empty_event]
- Returns:
- A dict mapping the event trigger to the var that is passed to the handler.
- """
- return {
- EventTriggers.ON_CLICK: lambda: [],
- EventTriggers.ON_MOUSE_MOVE: lambda: [],
- EventTriggers.ON_MOUSE_OVER: lambda: [],
- EventTriggers.ON_MOUSE_OUT: lambda: [],
- EventTriggers.ON_MOUSE_ENTER: lambda: [],
- EventTriggers.ON_MOUSE_LEAVE: lambda: [],
- }
+ # The customized event handler of mousedown on the the ticks of this axis.
+ on_mouse_down: EventHandler[empty_event]
+
+ # The customized event handler of mouseup on the ticks of this axis.
+ on_mouse_up: EventHandler[empty_event]
+
+ # The customized event handler of mousemove on the ticks of this axis.
+ on_mouse_move: EventHandler[empty_event]
+
+ # The customized event handler of mouseover on the ticks of this axis.
+ on_mouse_over: EventHandler[empty_event]
+
+ # The customized event handler of mouseout on the ticks of this axis.
+ on_mouse_out: EventHandler[empty_event]
+
+ # The customized event handler of moustenter on the ticks of this axis.
+ on_mouse_enter: EventHandler[empty_event]
+
+ # The customized event handler of mouseleave on the ticks of this axis.
+ on_mouse_leave: EventHandler[empty_event]
class PolarGrid(Recharts):
@@ -240,17 +308,17 @@ class PolarGrid(Recharts):
alias = "RechartsPolarGrid"
- # The x-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of container width.
- cx: Var[Union[int, str]]
+ # The x-coordinate of center.
+ cx: Var[int]
- # The y-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of container height.
- cy: Var[Union[int, str]]
+ # The y-coordinate of center.
+ cy: Var[int]
# The radius of the inner polar grid.
- inner_radius: Var[Union[int, str]]
+ inner_radius: Var[int]
# The radius of the outer polar grid.
- outer_radius: Var[Union[int, str]]
+ outer_radius: Var[int]
# The array of every line grid's angle.
polar_angles: Var[List[int]]
@@ -258,9 +326,12 @@ class PolarGrid(Recharts):
# The array of every line grid's radius.
polar_radius: Var[List[int]]
- # The type of polar grids. 'polygon' | 'circle'
+ # The type of polar grids. 'polygon' | 'circle'. Default: "polygon"
grid_type: Var[LiteralGridType]
+ # The stroke color of grid. Default: rx.color("gray", 10)
+ stroke: Var[Union[str, Color]] = LiteralVar.create(Color("gray", 10))
+
# Valid children components
_valid_children: List[str] = ["RadarChart", "RadiarBarChart"]
@@ -272,42 +343,48 @@ class PolarRadiusAxis(Recharts):
alias = "RechartsPolarRadiusAxis"
- # The angle of radial direction line to display axis text.
+ # The angle of radial direction line to display axis text. Default: 0
angle: Var[int]
- # The type of axis line. 'number' | 'category'
+ # The type of axis line. 'number' | 'category'. Default: "category"
type_: Var[LiteralPolarRadiusType]
- # Allow the axis has duplicated categorys or not when the type of axis is "category".
+ # Allow the axis has duplicated categorys or not when the type of axis is "category". Default: True
allow_duplicated_category: Var[bool]
# The x-coordinate of center.
- cx: Var[Union[int, str]]
+ cx: Var[int]
# The y-coordinate of center.
- cy: Var[Union[int, str]]
+ cy: Var[int]
- # If set to true, the ticks of this axis are reversed.
+ # If set to true, the ticks of this axis are reversed. Default: False
reversed: Var[bool]
- # The orientation of axis text.
- orientation: Var[str]
+ # The orientation of axis text. Default: "right"
+ orientation: Var[LiteralOrientationLeftRightMiddle]
- # If false set, axis line will not be drawn. If true set, axis line will be drawn which have the props calculated internally. If object set, axis line will be drawn which have the props mergered by the internal calculated props and the option.
+ # If false set, axis line will not be drawn. If true set, axis line will be drawn which have the props calculated internally. If object set, axis line will be drawn which have the props mergered by the internal calculated props and the option. Default: True
axis_line: Var[Union[bool, Dict[str, Any]]]
- # The width or height of tick.
- tick: Var[Union[int, str]]
+ # If false set, ticks will not be drawn. If true set, ticks will be drawn which have the props calculated internally. If object set, ticks will be drawn which have the props mergered by the internal calculated props and the option. Default: True
+ tick: Var[Union[bool, Dict[str, Any]]]
- # The count of ticks.
+ # The count of axis ticks. Not used if 'type' is 'category'. Default: 5
tick_count: Var[int]
- # If 'auto' set, the scale funtion is linear scale. 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utc' | 'sequential' | 'threshold'
+ # If 'auto' set, the scale funtion is linear scale. 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utc' | 'sequential' | 'threshold'. Default: "auto"
scale: Var[LiteralScale]
# Valid children components
_valid_children: List[str] = ["Label"]
+ # The domain of the polar radius axis, specifying the minimum and maximum values. Default: [0, "auto"]
+ domain: Var[List[Union[int, str]]]
+
+ # The stroke color of axis. Default: rx.color("gray", 10)
+ stroke: Var[Union[str, Color]] = LiteralVar.create(Color("gray", 10))
+
def get_event_triggers(self) -> dict[str, Union[Var, Any]]:
"""Get the event triggers that pass the component's value to the handler.
@@ -315,10 +392,18 @@ class PolarRadiusAxis(Recharts):
A dict mapping the event trigger to the var that is passed to the handler.
"""
return {
- EventTriggers.ON_CLICK: lambda: [],
- EventTriggers.ON_MOUSE_MOVE: lambda: [],
- EventTriggers.ON_MOUSE_OVER: lambda: [],
- EventTriggers.ON_MOUSE_OUT: lambda: [],
- EventTriggers.ON_MOUSE_ENTER: lambda: [],
- EventTriggers.ON_MOUSE_LEAVE: lambda: [],
+ EventTriggers.ON_CLICK: empty_event,
+ EventTriggers.ON_MOUSE_MOVE: empty_event,
+ EventTriggers.ON_MOUSE_OVER: empty_event,
+ EventTriggers.ON_MOUSE_OUT: empty_event,
+ EventTriggers.ON_MOUSE_ENTER: empty_event,
+ EventTriggers.ON_MOUSE_LEAVE: empty_event,
}
+
+
+pie = Pie.create
+radar = Radar.create
+radial_bar = RadialBar.create
+polar_angle_axis = PolarAngleAxis.create
+polar_grid = PolarGrid.create
+polar_radius_axis = PolarRadiusAxis.create
diff --git a/reflex/components/recharts/polar.pyi b/reflex/components/recharts/polar.pyi
index e2186eca0..025f8443d 100644
--- a/reflex/components/recharts/polar.pyi
+++ b/reflex/components/recharts/polar.pyi
@@ -1,20 +1,16 @@
"""Stub file for reflex/components/recharts/polar.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, Dict, List, Literal, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
+from reflex.constants.colors import Color
+from reflex.event import EventType
from reflex.style import Style
-from typing import Any, Dict, List, Union
-from reflex.constants import EventTriggers
-from reflex.vars import Var
+from reflex.vars.base import Var
+
from .recharts import (
- LiteralAnimationEasing,
- LiteralGridType,
- LiteralPolarRadiusType,
- LiteralScale,
Recharts,
)
@@ -25,68 +21,104 @@ class Pie(Recharts):
def create( # type: ignore
cls,
*children,
- data: Optional[Union[Var[List[Dict[str, Any]]], List[Dict[str, Any]]]] = None,
- data_key: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- cx: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- cy: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- inner_radius: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- outer_radius: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
+ data: Optional[Union[List[Dict[str, Any]], Var[List[Dict[str, Any]]]]] = None,
+ data_key: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ cx: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ cy: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ inner_radius: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ outer_radius: Optional[Union[Var[Union[int, str]], int, str]] = None,
start_angle: Optional[Union[Var[int], int]] = None,
end_angle: Optional[Union[Var[int], int]] = None,
min_angle: Optional[Union[Var[int], int]] = None,
padding_angle: Optional[Union[Var[int], int]] = None,
name_key: Optional[Union[Var[str], str]] = None,
- legend_type: Optional[Union[Var[str], str]] = None,
+ legend_type: Optional[
+ Union[
+ Literal[
+ "circle",
+ "cross",
+ "diamond",
+ "line",
+ "none",
+ "plainline",
+ "rect",
+ "square",
+ "star",
+ "triangle",
+ "wye",
+ ],
+ Var[
+ Literal[
+ "circle",
+ "cross",
+ "diamond",
+ "line",
+ "none",
+ "plainline",
+ "rect",
+ "square",
+ "star",
+ "triangle",
+ "wye",
+ ]
+ ],
+ ]
+ ] = None,
label: Optional[Union[Var[bool], bool]] = None,
label_line: Optional[Union[Var[bool], bool]] = None,
- fill: Optional[Union[Var[str], str]] = None,
- stroke: Optional[Union[Var[str], str]] = None,
+ stroke: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
+ fill: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
+ is_animation_active: Optional[Union[Var[bool], bool]] = None,
+ animation_begin: Optional[Union[Var[int], int]] = None,
+ animation_duration: Optional[Union[Var[int], int]] = None,
+ animation_easing: Optional[
+ Union[
+ Literal["ease", "ease-in", "ease-in-out", "ease-out", "linear"],
+ Var[Literal["ease", "ease-in", "ease-in-out", "ease-out", "linear"]],
+ ]
+ ] = None,
+ root_tab_index: Optional[Union[Var[int], int]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_animation_end: Optional[EventType[[]]] = None,
+ on_animation_start: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ **props,
) -> "Pie":
"""Create the component.
Args:
*children: The children of the component.
- data: data
+ data: The index of active sector in Pie, this option can be changed in mouse event handlers.
data_key: The key of each sector's value.
- cx: The x-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of container width.
- cy: The y-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of container height.
- inner_radius: The inner radius of pie, which can be set to a percent value.
- outer_radius: The outer radius of pie, which can be set to a percent value.
- start_angle: The angle of first sector.
- end_angle: The direction of sectors. 1 means clockwise and -1 means anticlockwise.
- min_angle: The minimum angle of each unzero data.
- padding_angle: The angle between two sectors.
- name_key: The key of each sector's name.
- legend_type: The type of icon in legend. If set to 'none', no legend item will be rendered.
- label: If false set, labels will not be drawn.
- label_line: If false set, label lines will not be drawn.
- fill: fill color
- stroke: stroke color
+ cx: The x-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of container width. Default: "50%"
+ cy: The y-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of container height. Default: "50%"
+ inner_radius: The inner radius of pie, which can be set to a percent value. Default: 0
+ outer_radius: The outer radius of pie, which can be set to a percent value. Default: "80%"
+ start_angle: The angle of first sector. Default: 0
+ end_angle: The end angle of last sector, which should be unequal to start_angle. Default: 360
+ min_angle: The minimum angle of each unzero data. Default: 0
+ padding_angle: The angle between two sectors. Default: 0
+ name_key: The key of each sector's name. Default: "name"
+ legend_type: The type of icon in legend. If set to 'none', no legend item will be rendered. Default: "rect"
+ label: If false set, labels will not be drawn. If true set, labels will be drawn which have the props calculated internally. Default: False
+ label_line: If false set, label lines will not be drawn. If true set, label lines will be drawn which have the props calculated internally. Default: False
+ stroke: Stoke color. Default: rx.color("accent", 9)
+ fill: Fill color. Default: rx.color("accent", 3)
+ is_animation_active: If set false, animation of tooltip will be disabled. Default: true in CSR, and false in SSR
+ animation_begin: Specifies when the animation should begin, the unit of this option is ms. Default: 400
+ animation_duration: Specifies the duration of animation, the unit of this option is ms. Default: 1500
+ animation_easing: The type of easing function. Default: "ease"
+ root_tab_index: The tabindex of wrapper surrounding the cells. Default: 0
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -101,25 +133,58 @@ class Pie(Recharts):
...
class Radar(Recharts):
+ def get_event_triggers(self) -> dict[str, Union[Var, Any]]: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- data_key: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- points: Optional[Union[Var[List[Dict[str, Any]]], List[Dict[str, Any]]]] = None,
+ data_key: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ points: Optional[Union[List[Dict[str, Any]], Var[List[Dict[str, Any]]]]] = None,
dot: Optional[Union[Var[bool], bool]] = None,
- stroke: Optional[Union[Var[str], str]] = None,
+ stroke: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
fill: Optional[Union[Var[str], str]] = None,
fill_opacity: Optional[Union[Var[float], float]] = None,
- legend_type: Optional[Union[Var[str], str]] = None,
+ legend_type: Optional[
+ Union[
+ Literal[
+ "circle",
+ "cross",
+ "diamond",
+ "line",
+ "none",
+ "plainline",
+ "rect",
+ "square",
+ "star",
+ "triangle",
+ "wye",
+ ],
+ Var[
+ Literal[
+ "circle",
+ "cross",
+ "diamond",
+ "line",
+ "none",
+ "plainline",
+ "rect",
+ "square",
+ "star",
+ "triangle",
+ "wye",
+ ]
+ ],
+ ]
+ ] = None,
label: Optional[Union[Var[bool], bool]] = None,
+ is_animation_active: Optional[Union[Var[bool], bool]] = None,
animation_begin: Optional[Union[Var[int], int]] = None,
animation_duration: Optional[Union[Var[int], int]] = None,
animation_easing: Optional[
Union[
- Var[Literal["ease", "ease-in", "ease-out", "ease-in-out", "linear"]],
- Literal["ease", "ease-in", "ease-out", "ease-in-out", "linear"],
+ Literal["ease", "ease-in", "ease-in-out", "ease-out", "linear"],
+ Var[Literal["ease", "ease-in", "ease-in-out", "ease-out", "linear"]],
]
] = None,
style: Optional[Style] = None,
@@ -128,52 +193,9 @@ class Radar(Recharts):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_animation_end: Optional[EventType[[]]] = None,
+ on_animation_start: Optional[EventType[[]]] = None,
+ **props,
) -> "Radar":
"""Create the component.
@@ -181,15 +203,16 @@ class Radar(Recharts):
*children: The children of the component.
data_key: The key of a group of data which should be unique in a radar chart.
points: The coordinates of all the vertexes of the radar shape, like [{ x, y }].
- dot: If false set, dots will not be drawn
- stroke: Stoke color
- fill: Fill color
- fill_opacity: opacity
- legend_type: The type of icon in legend. If set to 'none', no legend item will be rendered.
- label: If false set, labels will not be drawn
- animation_begin: Specifies when the animation should begin, the unit of this option is ms.
- animation_duration: Specifies the duration of animation, the unit of this option is ms.
- animation_easing: The type of easing function. 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'
+ dot: If false set, dots will not be drawn. Default: True
+ stroke: Stoke color. Default: rx.color("accent", 9)
+ fill: Fill color. Default: rx.color("accent", 3)
+ fill_opacity: opacity. Default: 0.6
+ legend_type: The type of icon in legend. If set to 'none', no legend item will be rendered. Default: "rect"
+ label: If false set, labels will not be drawn. Default: True
+ is_animation_active: If set false, animation of polygon will be disabled. Default: True in CSR, and False in SSR
+ animation_begin: Specifies when the animation should begin, the unit of this option is ms. Default: 0
+ animation_duration: Specifies the duration of animation, the unit of this option is ms. Default: 1500
+ animation_easing: The type of easing function. 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'. Default: "ease"
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -210,46 +233,86 @@ class RadialBar(Recharts):
def create( # type: ignore
cls,
*children,
- data: Optional[Union[Var[List[Dict[str, Any]]], List[Dict[str, Any]]]] = None,
+ data: Optional[Union[List[Dict[str, Any]], Var[List[Dict[str, Any]]]]] = None,
+ data_key: Optional[Union[Var[Union[int, str]], int, str]] = None,
min_angle: Optional[Union[Var[int], int]] = None,
- legend_type: Optional[Union[Var[str], str]] = None,
- label: Optional[Union[Var[bool], bool]] = None,
- background: Optional[Union[Var[bool], bool]] = None,
+ legend_type: Optional[
+ Union[
+ Literal[
+ "circle",
+ "cross",
+ "diamond",
+ "line",
+ "none",
+ "plainline",
+ "rect",
+ "square",
+ "star",
+ "triangle",
+ "wye",
+ ],
+ Var[
+ Literal[
+ "circle",
+ "cross",
+ "diamond",
+ "line",
+ "none",
+ "plainline",
+ "rect",
+ "square",
+ "star",
+ "triangle",
+ "wye",
+ ]
+ ],
+ ]
+ ] = None,
+ label: Optional[
+ Union[Dict[str, Any], Var[Union[Dict[str, Any], bool]], bool]
+ ] = None,
+ background: Optional[
+ Union[Dict[str, Any], Var[Union[Dict[str, Any], bool]], bool]
+ ] = None,
+ is_animation_active: Optional[Union[Var[bool], bool]] = None,
+ animation_begin: Optional[Union[Var[int], int]] = None,
+ animation_duration: Optional[Union[Var[int], int]] = None,
+ animation_easing: Optional[
+ Union[
+ Literal["ease", "ease-in", "ease-in-out", "ease-out", "linear"],
+ Var[Literal["ease", "ease-in", "ease-in-out", "ease-out", "linear"]],
+ ]
+ ] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_animation_end: Optional[EventType[[]]] = None,
+ on_animation_start: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ **props,
) -> "RadialBar":
"""Create the component.
Args:
*children: The children of the component.
data: The source data which each element is an object.
- min_angle: Min angle of each bar. A positive value between 0 and 360.
- legend_type: Type of legend
- label: If false set, labels will not be drawn.
- background: If false set, background sector will not be drawn.
+ data_key: The key of a group of data which should be unique to show the meaning of angle axis.
+ min_angle: Min angle of each bar. A positive value between 0 and 360. Default: 0
+ legend_type: The type of icon in legend. If set to 'none', no legend item will be rendered. Default: "rect"
+ label: If false set, labels will not be drawn. If true set, labels will be drawn which have the props calculated internally. Default: False
+ background: If false set, background sector will not be drawn. Default: False
+ is_animation_active: If set false, animation of radial bars will be disabled. Default: True
+ animation_begin: Specifies when the animation should begin, the unit of this option is ms. Default: 0
+ animation_duration: Specifies the duration of animation, the unit of this option is ms. Default 1500
+ animation_easing: The type of easing function. 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'. Default: "ease"
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -264,26 +327,30 @@ class RadialBar(Recharts):
...
class PolarAngleAxis(Recharts):
- def get_event_triggers(self) -> dict[str, Union[Var, Any]]: ...
@overload
@classmethod
def create( # type: ignore
cls,
*children,
- data_key: Optional[Union[Var[Union[str, int]], Union[str, int]]] = None,
- cx: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- cy: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- radius: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
+ data_key: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ cx: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ cy: Optional[Union[Var[Union[int, str]], int, str]] = None,
+ radius: Optional[Union[Var[Union[int, str]], int, str]] = None,
axis_line: Optional[
- Union[Var[Union[bool, Dict[str, Any]]], Union[bool, Dict[str, Any]]]
+ Union[Dict[str, Any], Var[Union[Dict[str, Any], bool]], bool]
+ ] = None,
+ axis_line_type: Optional[
+ Union[Literal["circle", "polygon"], Var[Literal["circle", "polygon"]]]
] = None,
- axis_line_type: Optional[Union[Var[str], str]] = None,
tick_line: Optional[
- Union[Var[Union[bool, Dict[str, Any]]], Union[bool, Dict[str, Any]]]
+ Union[Dict[str, Any], Var[Union[Dict[str, Any], bool]], bool]
] = None,
- tick: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- ticks: Optional[Union[Var[List[Dict[str, Any]]], List[Dict[str, Any]]]] = None,
- orient: Optional[Union[Var[str], str]] = None,
+ tick: Optional[
+ Union[Dict[str, Any], Var[Union[Dict[str, Any], bool]], bool]
+ ] = None,
+ ticks: Optional[Union[List[Dict[str, Any]], Var[List[Dict[str, Any]]]]] = None,
+ orientation: Optional[Union[Var[str], str]] = None,
+ stroke: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
allow_duplicated_category: Optional[Union[Var[bool], bool]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
@@ -291,25 +358,22 @@ class PolarAngleAxis(Recharts):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "PolarAngleAxis":
"""Create the component.
@@ -319,13 +383,22 @@ class PolarAngleAxis(Recharts):
cx: The x-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of container width.
cy: The y-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of container height.
radius: The outer radius of circle grid. If set a percentage, the final value is obtained by multiplying the percentage of maxRadius which is calculated by the width, height, cx, cy.
- axis_line: If false set, axis line will not be drawn. If true set, axis line will be drawn which have the props calculated internally. If object set, axis line will be drawn which have the props mergered by the internal calculated props and the option.
- axis_line_type: The type of axis line.
- tick_line: If false set, tick lines will not be drawn. If true set, tick lines will be drawn which have the props calculated internally. If object set, tick lines will be drawn which have the props mergered by the internal calculated props and the option.
- tick: The width or height of tick.
+ axis_line: If false set, axis line will not be drawn. If true set, axis line will be drawn which have the props calculated internally. If object set, axis line will be drawn which have the props mergered by the internal calculated props and the option. Default: True
+ axis_line_type: The type of axis line. Default: "polygon"
+ tick_line: If false set, tick lines will not be drawn. If true set, tick lines will be drawn which have the props calculated internally. If object set, tick lines will be drawn which have the props mergered by the internal calculated props and the option. Default: False
+ tick: If false set, ticks will not be drawn. If true set, ticks will be drawn which have the props calculated internally. If object set, ticks will be drawn which have the props mergered by the internal calculated props and the option. Default: True
ticks: The array of every tick's value and angle.
- orient: The orientation of axis text.
- allow_duplicated_category: Allow the axis has duplicated categorys or not when the type of axis is "category".
+ orientation: The orientation of axis text. Default: "outer"
+ stroke: The stroke color of axis. Default: rx.color("gray", 10)
+ allow_duplicated_category: Allow the axis has duplicated categorys or not when the type of axis is "category". Default: True
+ on_click: The customized event handler of click on the ticks of this axis.
+ on_mouse_down: The customized event handler of mousedown on the the ticks of this axis.
+ on_mouse_up: The customized event handler of mouseup on the ticks of this axis.
+ on_mouse_move: The customized event handler of mousemove on the ticks of this axis.
+ on_mouse_over: The customized event handler of mouseover on the ticks of this axis.
+ on_mouse_out: The customized event handler of mouseout on the ticks of this axis.
+ on_mouse_enter: The customized event handler of moustenter on the ticks of this axis.
+ on_mouse_leave: The customized event handler of mouseleave on the ticks of this axis.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -345,79 +418,51 @@ class PolarGrid(Recharts):
def create( # type: ignore
cls,
*children,
- cx: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- cy: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- inner_radius: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- outer_radius: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- polar_angles: Optional[Union[Var[List[int]], List[int]]] = None,
- polar_radius: Optional[Union[Var[List[int]], List[int]]] = None,
+ cx: Optional[Union[Var[int], int]] = None,
+ cy: Optional[Union[Var[int], int]] = None,
+ inner_radius: Optional[Union[Var[int], int]] = None,
+ outer_radius: Optional[Union[Var[int], int]] = None,
+ polar_angles: Optional[Union[List[int], Var[List[int]]]] = None,
+ polar_radius: Optional[Union[List[int], Var[List[int]]]] = None,
grid_type: Optional[
- Union[Var[Literal["polygon", "circle"]], Literal["polygon", "circle"]]
+ Union[Literal["circle", "polygon"], Var[Literal["circle", "polygon"]]]
] = None,
+ stroke: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "PolarGrid":
"""Create the component.
Args:
*children: The children of the component.
- cx: The x-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of container width.
- cy: The y-coordinate of center. If set a percentage, the final value is obtained by multiplying the percentage of container height.
+ cx: The x-coordinate of center.
+ cy: The y-coordinate of center.
inner_radius: The radius of the inner polar grid.
outer_radius: The radius of the outer polar grid.
polar_angles: The array of every line grid's angle.
polar_radius: The array of every line grid's radius.
- grid_type: The type of polar grids. 'polygon' | 'circle'
+ grid_type: The type of polar grids. 'polygon' | 'circle'. Default: "polygon"
+ stroke: The stroke color of grid. Default: rx.color("gray", 10)
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -440,99 +485,100 @@ class PolarRadiusAxis(Recharts):
*children,
angle: Optional[Union[Var[int], int]] = None,
type_: Optional[
- Union[Var[Literal["number", "category"]], Literal["number", "category"]]
+ Union[Literal["category", "number"], Var[Literal["category", "number"]]]
] = None,
allow_duplicated_category: Optional[Union[Var[bool], bool]] = None,
- cx: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
- cy: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
+ cx: Optional[Union[Var[int], int]] = None,
+ cy: Optional[Union[Var[int], int]] = None,
reversed: Optional[Union[Var[bool], bool]] = None,
- orientation: Optional[Union[Var[str], str]] = None,
- axis_line: Optional[
- Union[Var[Union[bool, Dict[str, Any]]], Union[bool, Dict[str, Any]]]
+ orientation: Optional[
+ Union[
+ Literal["left", "middle", "right"],
+ Var[Literal["left", "middle", "right"]],
+ ]
+ ] = None,
+ axis_line: Optional[
+ Union[Dict[str, Any], Var[Union[Dict[str, Any], bool]], bool]
+ ] = None,
+ tick: Optional[
+ Union[Dict[str, Any], Var[Union[Dict[str, Any], bool]], bool]
] = None,
- tick: Optional[Union[Var[Union[int, str]], Union[int, str]]] = None,
tick_count: Optional[Union[Var[int], int]] = None,
scale: Optional[
Union[
+ Literal[
+ "auto",
+ "band",
+ "identity",
+ "linear",
+ "log",
+ "ordinal",
+ "point",
+ "pow",
+ "quantile",
+ "quantize",
+ "sequential",
+ "sqrt",
+ "threshold",
+ "time",
+ "utc",
+ ],
Var[
Literal[
"auto",
- "linear",
- "pow",
- "sqrt",
- "log",
- "identity",
- "time",
"band",
- "point",
+ "identity",
+ "linear",
+ "log",
"ordinal",
+ "point",
+ "pow",
"quantile",
"quantize",
- "utc",
"sequential",
+ "sqrt",
"threshold",
+ "time",
+ "utc",
]
],
- Literal[
- "auto",
- "linear",
- "pow",
- "sqrt",
- "log",
- "identity",
- "time",
- "band",
- "point",
- "ordinal",
- "quantile",
- "quantize",
- "utc",
- "sequential",
- "threshold",
- ],
]
] = None,
+ domain: Optional[
+ Union[List[Union[int, str]], Var[List[Union[int, str]]]]
+ ] = None,
+ stroke: Optional[Union[Color, Var[Union[Color, str]], str]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
id: Optional[Any] = None,
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_click: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ **props,
) -> "PolarRadiusAxis":
"""Create the component.
Args:
*children: The children of the component.
- angle: The angle of radial direction line to display axis text.
- type_: The type of axis line. 'number' | 'category'
- allow_duplicated_category: Allow the axis has duplicated categorys or not when the type of axis is "category".
+ angle: The angle of radial direction line to display axis text. Default: 0
+ type_: The type of axis line. 'number' | 'category'. Default: "category"
+ allow_duplicated_category: Allow the axis has duplicated categorys or not when the type of axis is "category". Default: True
cx: The x-coordinate of center.
cy: The y-coordinate of center.
- reversed: If set to true, the ticks of this axis are reversed.
- orientation: The orientation of axis text.
- axis_line: If false set, axis line will not be drawn. If true set, axis line will be drawn which have the props calculated internally. If object set, axis line will be drawn which have the props mergered by the internal calculated props and the option.
- tick: The width or height of tick.
- tick_count: The count of ticks.
- scale: If 'auto' set, the scale funtion is linear scale. 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utc' | 'sequential' | 'threshold'
+ reversed: If set to true, the ticks of this axis are reversed. Default: False
+ orientation: The orientation of axis text. Default: "right"
+ axis_line: If false set, axis line will not be drawn. If true set, axis line will be drawn which have the props calculated internally. If object set, axis line will be drawn which have the props mergered by the internal calculated props and the option. Default: True
+ tick: If false set, ticks will not be drawn. If true set, ticks will be drawn which have the props calculated internally. If object set, ticks will be drawn which have the props mergered by the internal calculated props and the option. Default: True
+ tick_count: The count of axis ticks. Not used if 'type' is 'category'. Default: 5
+ scale: If 'auto' set, the scale funtion is linear scale. 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utc' | 'sequential' | 'threshold'. Default: "auto"
+ domain: The domain of the polar radius axis, specifying the minimum and maximum values. Default: [0, "auto"]
+ stroke: The stroke color of axis. Default: rx.color("gray", 10)
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
@@ -545,3 +591,10 @@ class PolarRadiusAxis(Recharts):
The component.
"""
...
+
+pie = Pie.create
+radar = Radar.create
+radial_bar = RadialBar.create
+polar_angle_axis = PolarAngleAxis.create
+polar_grid = PolarGrid.create
+polar_radius_axis = PolarRadiusAxis.create
diff --git a/reflex/components/recharts/recharts.py b/reflex/components/recharts/recharts.py
index 28c8a5c8a..a0d683f72 100644
--- a/reflex/components/recharts/recharts.py
+++ b/reflex/components/recharts/recharts.py
@@ -1,19 +1,35 @@
"""A component that wraps a recharts lib."""
-from typing import Literal
+
+from typing import Dict, Literal
from reflex.components.component import Component, MemoizationLeaf, NoSSRComponent
+from reflex.utils import console
class Recharts(Component):
"""A component that wraps a recharts lib."""
- library = "recharts@2.8.0"
+ library = "recharts@2.13.0"
+
+ def render(self) -> Dict:
+ """Render the tag.
+
+ Returns:
+ The rendered tag.
+ """
+ tag = super().render()
+ if any(p.startswith("css") for p in tag["props"]):
+ console.warn(
+ f"CSS props do not work for {self.__class__.__name__}. Consult docs to style it with its own prop."
+ )
+ tag["props"] = [p for p in tag["props"] if not p.startswith("css")]
+ return tag
class RechartsCharts(NoSSRComponent, MemoizationLeaf):
"""A component that wraps a recharts lib."""
- library = "recharts@2.8.0"
+ library = "recharts@2.13.0"
LiteralAnimationEasing = Literal["ease", "ease-in", "ease-out", "ease-in-out", "linear"]
@@ -25,6 +41,7 @@ LiteralLineType = Literal["joint", "fitting"]
LiteralOrientation = Literal["top", "bottom", "left", "right", "middle"]
LiteralOrientationLeftRightMiddle = Literal["left", "right", "middle"]
LiteralOrientationTopBottom = Literal["top", "bottom"]
+LiteralOrientationLeftRight = Literal["left", "right"]
LiteralOrientationTopBottomLeftRight = Literal["top", "bottom", "left", "right"]
LiteralScale = Literal[
"auto",
@@ -43,6 +60,7 @@ LiteralScale = Literal[
"sequential",
"threshold",
]
+LiteralTextAnchor = Literal["start", "middle", "end"]
LiteralLayout = Literal["horizontal", "vertical"]
LiteralPolarRadiusType = Literal["number", "category"]
LiteralGridType = Literal["polygon", "circle"]
@@ -78,7 +96,7 @@ LiteralIconType = Literal[
"triangle",
"wye",
]
-LiteralLegendType = [
+LiteralLegendType = Literal[
"line",
"plainline",
"square",
@@ -114,6 +132,9 @@ LiteralAreaType = Literal[
"stepBefore",
"stepAfter",
]
-LiteralDirection = Literal["x", "y", "both"]
+LiteralDirection = Literal["x", "y"]
LiteralInterval = Literal["preserveStart", "preserveEnd", "preserveStartEnd"]
+LiteralIntervalAxis = Literal[
+ "preserveStart", "preserveEnd", "preserveStartEnd", "equidistantPreserveStart"
+]
LiteralSyncMethod = Literal["index", "value"]
diff --git a/reflex/components/recharts/recharts.pyi b/reflex/components/recharts/recharts.pyi
index ff279a50a..c13519f05 100644
--- a/reflex/components/recharts/recharts.pyi
+++ b/reflex/components/recharts/recharts.pyi
@@ -1,16 +1,17 @@
"""Stub file for reflex/components/recharts/recharts.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Literal
+
from reflex.components.component import Component, MemoizationLeaf, NoSSRComponent
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.vars.base import Var
class Recharts(Component):
+ def render(self) -> Dict: ...
@overload
@classmethod
def create( # type: ignore
@@ -22,52 +23,22 @@ class Recharts(Component):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Recharts":
"""Create the component.
@@ -98,52 +69,22 @@ class RechartsCharts(NoSSRComponent, MemoizationLeaf):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "RechartsCharts":
"""Create a new memoization leaf component.
@@ -171,6 +112,7 @@ LiteralLineType = Literal["joint", "fitting"]
LiteralOrientation = Literal["top", "bottom", "left", "right", "middle"]
LiteralOrientationLeftRightMiddle = Literal["left", "right", "middle"]
LiteralOrientationTopBottom = Literal["top", "bottom"]
+LiteralOrientationLeftRight = Literal["left", "right"]
LiteralOrientationTopBottomLeftRight = Literal["top", "bottom", "left", "right"]
LiteralScale = Literal[
"auto",
@@ -189,6 +131,7 @@ LiteralScale = Literal[
"sequential",
"threshold",
]
+LiteralTextAnchor = Literal["start", "middle", "end"]
LiteralLayout = Literal["horizontal", "vertical"]
LiteralPolarRadiusType = Literal["number", "category"]
LiteralGridType = Literal["polygon", "circle"]
@@ -224,7 +167,7 @@ LiteralIconType = Literal[
"triangle",
"wye",
]
-LiteralLegendType = [
+LiteralLegendType = Literal[
"line",
"plainline",
"square",
@@ -260,6 +203,9 @@ LiteralAreaType = Literal[
"stepBefore",
"stepAfter",
]
-LiteralDirection = Literal["x", "y", "both"]
+LiteralDirection = Literal["x", "y"]
LiteralInterval = Literal["preserveStart", "preserveEnd", "preserveStartEnd"]
+LiteralIntervalAxis = Literal[
+ "preserveStart", "preserveEnd", "preserveStartEnd", "equidistantPreserveStart"
+]
LiteralSyncMethod = Literal["index", "value"]
diff --git a/reflex/components/sonner/toast.py b/reflex/components/sonner/toast.py
index 8a6c59a54..175c68f63 100644
--- a/reflex/components/sonner/toast.py
+++ b/reflex/components/sonner/toast.py
@@ -2,17 +2,22 @@
from __future__ import annotations
-from typing import Literal
+from typing import Any, ClassVar, Literal, Optional, Union
from reflex.base import Base
from reflex.components.component import Component, ComponentNamespace
from reflex.components.lucide.icon import Icon
-from reflex.event import EventSpec, call_script
-from reflex.style import Style, color_mode
+from reflex.components.props import NoExtrasAllowedProps, PropsBase
+from reflex.event import (
+ EventSpec,
+ call_script,
+)
+from reflex.style import Style, resolved_color_mode
from reflex.utils import format
from reflex.utils.imports import ImportVar
-from reflex.utils.serializers import serialize
-from reflex.vars import Var, VarData
+from reflex.utils.serializers import serializer
+from reflex.vars import VarData
+from reflex.vars.base import LiteralVar, Var
LiteralPosition = Literal[
"top-left",
@@ -23,50 +28,74 @@ LiteralPosition = Literal[
"bottom-right",
]
-
-toast_ref = Var.create_safe("refs['__toast']")
+toast_ref = Var(_js_expr="refs['__toast']")
-class PropsBase(Base):
- """Base class for all props classes."""
+class ToastAction(Base):
+ """A toast action that render a button in the toast."""
- def json(self) -> str:
- """Convert the object to a json string.
+ label: str
+ on_click: Any
- Returns:
- The object as a json string.
- """
- from reflex.utils.serializers import serialize
- return self.__config__.json_dumps(
- {format.to_camel_case(key): value for key, value in self.dict().items()},
- default=serialize,
+@serializer
+def serialize_action(action: ToastAction) -> dict:
+ """Serialize a toast action.
+
+ Args:
+ action: The toast action to serialize.
+
+ Returns:
+ The serialized toast action with on_click formatted to queue the given event.
+ """
+ return {
+ "label": action.label,
+ "onClick": format.format_queue_events(action.on_click),
+ }
+
+
+def _toast_callback_signature(toast: Var) -> list[Var]:
+ """The signature for the toast callback, stripping out unserializable keys.
+
+ Args:
+ toast: The toast variable.
+
+ Returns:
+ A function call stripping non-serializable members of the toast object.
+ """
+ return [
+ Var(
+ _js_expr=f"(() => {{let {{action, cancel, onDismiss, onAutoClose, ...rest}} = {str(toast)}; return rest}})()"
)
+ ]
-class ToastProps(PropsBase):
+class ToastProps(PropsBase, NoExtrasAllowedProps):
"""Props for the toast component."""
+ # Toast's title, renders above the description.
+ title: Optional[Union[str, Var]]
+
# Toast's description, renders underneath the title.
- description: str = ""
+ description: Optional[Union[str, Var]]
# Whether to show the close button.
- close_button: bool = False
+ close_button: Optional[bool]
# Dark toast in light mode and vice versa.
- invert: bool = False
+ invert: Optional[bool]
# Control the sensitivity of the toast for screen readers
- important: bool = False
+ important: Optional[bool]
# Time in milliseconds that should elapse before automatically closing the toast.
- duration: int = 4000
+ duration: Optional[int]
# Position of the toast.
- position: LiteralPosition = "bottom-right"
+ position: Optional[LiteralPosition]
# If false, it'll prevent the user from dismissing the toast.
- dismissible: bool = True
+ dismissible: Optional[bool]
# TODO: fix serialization of icons for toast? (might not be possible yet)
# Icon displayed in front of toast's text, aligned vertically.
@@ -74,51 +103,89 @@ class ToastProps(PropsBase):
# TODO: fix implementation for action / cancel buttons
# Renders a primary button, clicking it will close the toast.
- # action: str = ""
+ action: Optional[ToastAction]
# Renders a secondary button, clicking it will close the toast.
- # cancel: str = ""
+ cancel: Optional[ToastAction]
# Custom id for the toast.
- id: str = ""
+ id: Optional[Union[str, Var]]
# Removes the default styling, which allows for easier customization.
- unstyled: bool = False
+ unstyled: Optional[bool]
# Custom style for the toast.
- style: Style = Style()
+ style: Optional[Style]
+ # XXX: These still do not seem to work
# Custom style for the toast primary button.
- # action_button_styles: Style = Style()
+ action_button_styles: Optional[Style]
# Custom style for the toast secondary button.
- # cancel_button_styles: Style = Style()
+ cancel_button_styles: Optional[Style]
+
+ # The function gets called when either the close button is clicked, or the toast is swiped.
+ on_dismiss: Optional[Any]
+
+ # Function that gets called when the toast disappears automatically after it's timeout (duration` prop).
+ on_auto_close: Optional[Any]
+
+ def dict(self, *args, **kwargs) -> dict[str, Any]:
+ """Convert the object to a dictionary.
+
+ Args:
+ *args: The arguments to pass to the base class.
+ **kwargs: The keyword arguments to pass to the base
+
+ Returns:
+ The object as a dictionary with ToastAction fields intact.
+ """
+ kwargs.setdefault("exclude_none", True) # type: ignore
+ d = super().dict(*args, **kwargs)
+ # Keep these fields as ToastAction so they can be serialized specially
+ if "action" in d:
+ d["action"] = self.action
+ if isinstance(self.action, dict):
+ d["action"] = ToastAction(**self.action)
+ if "cancel" in d:
+ d["cancel"] = self.cancel
+ if isinstance(self.cancel, dict):
+ d["cancel"] = ToastAction(**self.cancel)
+ if "onDismiss" in d:
+ d["onDismiss"] = format.format_queue_events(
+ self.on_dismiss, _toast_callback_signature
+ )
+ if "onAutoClose" in d:
+ d["onAutoClose"] = format.format_queue_events(
+ self.on_auto_close, _toast_callback_signature
+ )
+ return d
class Toaster(Component):
"""A Toaster Component for displaying toast notifications."""
- library = "sonner@1.4.41"
+ library: str = "sonner@1.5.0"
tag = "Toaster"
# the theme of the toast
- theme: Var[str] = color_mode
+ theme: Var[str] = resolved_color_mode
# whether to show rich colors
- rich_colors: Var[bool] = Var.create_safe(True)
+ rich_colors: Var[bool] = LiteralVar.create(True)
# whether to expand the toast
- expand: Var[bool] = Var.create_safe(True)
+ expand: Var[bool] = LiteralVar.create(True)
# the number of toasts that are currently visible
visible_toasts: Var[int]
# the position of the toast
- position: Var[LiteralPosition] = Var.create_safe("bottom-right")
+ position: Var[LiteralPosition] = LiteralVar.create("bottom-right")
# whether to show the close button
- close_button: Var[bool] = Var.create_safe(False)
+ close_button: Var[bool] = LiteralVar.create(False)
# offset of the toast
offset: Var[str]
@@ -144,18 +211,28 @@ class Toaster(Component):
# Pauses toast timers when the page is hidden, e.g., when the tab is backgrounded, the browser is minimized, or the OS is locked.
pause_when_page_is_hidden: Var[bool]
- def _get_hooks(self) -> Var[str]:
- hook = Var.create_safe(f"{toast_ref} = toast", _var_is_local=True)
- hook._var_data = VarData( # type: ignore
- imports={
- "/utils/state": [ImportVar(tag="refs")],
- self.library: [ImportVar(tag="toast", install=False)],
- }
+ # Marked True when any Toast component is created.
+ is_used: ClassVar[bool] = False
+
+ def add_hooks(self) -> list[Var | str]:
+ """Add hooks for the toaster component.
+
+ Returns:
+ The hooks for the toaster component.
+ """
+ hook = Var(
+ _js_expr=f"{toast_ref} = toast",
+ _var_data=VarData(
+ imports={
+ "$/utils/state": [ImportVar(tag="refs")],
+ self.library: [ImportVar(tag="toast", install=False)],
+ }
+ ),
)
- return hook
+ return [hook]
@staticmethod
- def send_toast(message: str, level: str | None = None, **props) -> EventSpec:
+ def send_toast(message: str = "", level: str | None = None, **props) -> EventSpec:
"""Send a toast message.
Args:
@@ -163,21 +240,30 @@ class Toaster(Component):
level: The level of the toast.
**props: The options for the toast.
+ Raises:
+ ValueError: If the Toaster component is not created.
+
Returns:
The toast event.
"""
+ if not Toaster.is_used:
+ raise ValueError(
+ "Toaster component must be created before sending a toast. (use `rx.toast.provider()`)"
+ )
toast_command = f"{toast_ref}.{level}" if level is not None else toast_ref
+ if message == "" and ("title" not in props or "description" not in props):
+ raise ValueError("Toast message or title or description must be provided.")
if props:
- args = serialize(ToastProps(**props))
- toast = f"{toast_command}(`{message}`, {args})"
+ args = LiteralVar.create(ToastProps(component_name="rx.toast", **props)) # type: ignore
+ toast = f"{toast_command}(`{message}`, {str(args)})"
else:
toast = f"{toast_command}(`{message}`)"
- toast_action = Var.create(toast, _var_is_string=False, _var_is_local=True)
- return call_script(toast_action) # type: ignore
+ toast_action = Var(_js_expr=toast)
+ return call_script(toast_action)
@staticmethod
- def toast_info(message: str, **kwargs):
+ def toast_info(message: str = "", **kwargs):
"""Display an info toast message.
Args:
@@ -190,7 +276,7 @@ class Toaster(Component):
return Toaster.send_toast(message, level="info", **kwargs)
@staticmethod
- def toast_warning(message: str, **kwargs):
+ def toast_warning(message: str = "", **kwargs):
"""Display a warning toast message.
Args:
@@ -203,7 +289,7 @@ class Toaster(Component):
return Toaster.send_toast(message, level="warning", **kwargs)
@staticmethod
- def toast_error(message: str, **kwargs):
+ def toast_error(message: str = "", **kwargs):
"""Display an error toast message.
Args:
@@ -216,7 +302,7 @@ class Toaster(Component):
return Toaster.send_toast(message, level="error", **kwargs)
@staticmethod
- def toast_success(message: str, **kwargs):
+ def toast_success(message: str = "", **kwargs):
"""Display a success toast message.
Args:
@@ -228,7 +314,8 @@ class Toaster(Component):
"""
return Toaster.send_toast(message, level="success", **kwargs)
- def toast_dismiss(self, id: str | None):
+ @staticmethod
+ def toast_dismiss(id: Var | str | None = None):
"""Dismiss a toast.
Args:
@@ -237,12 +324,33 @@ class Toaster(Component):
Returns:
The toast dismiss event.
"""
- if id is None:
- dismiss = f"{toast_ref}.dismiss()"
+ dismiss_var_data = None
+
+ if isinstance(id, Var):
+ dismiss = f"{toast_ref}.dismiss({str(id)})"
+ dismiss_var_data = id._get_all_var_data()
+ elif isinstance(id, str):
+ dismiss = f"{toast_ref}.dismiss('{id}')"
else:
- dismiss = f"{toast_ref}.dismiss({id})"
- dismiss_action = Var.create(dismiss, _var_is_string=False, _var_is_local=True)
- return call_script(dismiss_action) # type: ignore
+ dismiss = f"{toast_ref}.dismiss()"
+ dismiss_action = Var(
+ _js_expr=dismiss, _var_data=VarData.merge(dismiss_var_data)
+ )
+ return call_script(dismiss_action)
+
+ @classmethod
+ def create(cls, *children, **props) -> Component:
+ """Create a toaster component.
+
+ Args:
+ *children: The children of the toaster.
+ **props: The properties of the toaster.
+
+ Returns:
+ The toaster component.
+ """
+ cls.is_used = True
+ return super().create(*children, **props)
# TODO: figure out why loading toast stay open forever
diff --git a/reflex/components/sonner/toast.pyi b/reflex/components/sonner/toast.pyi
index 2bf937703..10168257e 100644
--- a/reflex/components/sonner/toast.pyi
+++ b/reflex/components/sonner/toast.pyi
@@ -1,22 +1,18 @@
"""Stub file for reflex/components/sonner/toast.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
+from typing import Any, ClassVar, Dict, Literal, Optional, Union, overload
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-from typing import Literal
from reflex.base import Base
from reflex.components.component import Component, ComponentNamespace
from reflex.components.lucide.icon import Icon
-from reflex.event import EventSpec, call_script
-from reflex.style import Style, color_mode
-from reflex.utils import format
-from reflex.utils.imports import ImportVar
-from reflex.utils.serializers import serialize
-from reflex.vars import Var, VarData
+from reflex.components.props import NoExtrasAllowedProps, PropsBase
+from reflex.event import EventSpec, EventType
+from reflex.style import Style
+from reflex.utils.serializers import serializer
+from reflex.vars.base import Var
LiteralPosition = Literal[
"top-left",
@@ -26,35 +22,54 @@ LiteralPosition = Literal[
"bottom-center",
"bottom-right",
]
-toast_ref = Var.create_safe("refs['__toast']")
+toast_ref = Var(_js_expr="refs['__toast']")
-class PropsBase(Base):
- def json(self) -> str: ...
+class ToastAction(Base):
+ label: str
+ on_click: Any
-class ToastProps(PropsBase):
- description: str
- close_button: bool
- invert: bool
- important: bool
- duration: int
- position: LiteralPosition
- dismissible: bool
- id: str
- unstyled: bool
- style: Style
+@serializer
+def serialize_action(action: ToastAction) -> dict: ...
+
+class ToastProps(PropsBase, NoExtrasAllowedProps):
+ title: Optional[Union[str, Var]]
+ description: Optional[Union[str, Var]]
+ close_button: Optional[bool]
+ invert: Optional[bool]
+ important: Optional[bool]
+ duration: Optional[int]
+ position: Optional[LiteralPosition]
+ dismissible: Optional[bool]
+ action: Optional[ToastAction]
+ cancel: Optional[ToastAction]
+ id: Optional[Union[str, Var]]
+ unstyled: Optional[bool]
+ style: Optional[Style]
+ action_button_styles: Optional[Style]
+ cancel_button_styles: Optional[Style]
+ on_dismiss: Optional[Any]
+ on_auto_close: Optional[Any]
+
+ def dict(self, *args, **kwargs) -> dict[str, Any]: ...
class Toaster(Component):
+ is_used: ClassVar[bool] = False
+
+ def add_hooks(self) -> list[Var | str]: ...
@staticmethod
- def send_toast(message: str, level: str | None = None, **props) -> EventSpec: ...
+ def send_toast(
+ message: str = "", level: str | None = None, **props
+ ) -> EventSpec: ...
@staticmethod
- def toast_info(message: str, **kwargs): ...
+ def toast_info(message: str = "", **kwargs): ...
@staticmethod
- def toast_warning(message: str, **kwargs): ...
+ def toast_warning(message: str = "", **kwargs): ...
@staticmethod
- def toast_error(message: str, **kwargs): ...
+ def toast_error(message: str = "", **kwargs): ...
@staticmethod
- def toast_success(message: str, **kwargs): ...
- def toast_dismiss(self, id: str | None): ...
+ def toast_success(message: str = "", **kwargs): ...
+ @staticmethod
+ def toast_dismiss(id: Var | str | None = None): ...
@overload
@classmethod
def create( # type: ignore
@@ -66,24 +81,24 @@ class Toaster(Component):
visible_toasts: Optional[Union[Var[int], int]] = None,
position: Optional[
Union[
+ Literal[
+ "bottom-center",
+ "bottom-left",
+ "bottom-right",
+ "top-center",
+ "top-left",
+ "top-right",
+ ],
Var[
Literal[
- "top-left",
- "top-center",
- "top-right",
- "bottom-left",
"bottom-center",
+ "bottom-left",
"bottom-right",
+ "top-center",
+ "top-left",
+ "top-right",
]
],
- Literal[
- "top-left",
- "top-center",
- "top-right",
- "bottom-left",
- "bottom-center",
- "bottom-right",
- ],
]
] = None,
close_button: Optional[Union[Var[bool], bool]] = None,
@@ -91,9 +106,9 @@ class Toaster(Component):
dir: Optional[Union[Var[str], str]] = None,
hotkey: Optional[Union[Var[str], str]] = None,
invert: Optional[Union[Var[bool], bool]] = None,
- toast_options: Optional[Union[Var[ToastProps], ToastProps]] = None,
+ toast_options: Optional[Union[ToastProps, Var[ToastProps]]] = None,
gap: Optional[Union[Var[int], int]] = None,
- loading_icon: Optional[Union[Var[Icon], Icon]] = None,
+ loading_icon: Optional[Union[Icon, Var[Icon]]] = None,
pause_when_page_is_hidden: Optional[Union[Var[bool], bool]] = None,
style: Optional[Style] = None,
key: Optional[Any] = None,
@@ -101,57 +116,27 @@ class Toaster(Component):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
) -> "Toaster":
- """Create the component.
+ """Create a toaster component.
Args:
- *children: The children of the component.
+ *children: The children of the toaster.
theme: the theme of the toast
rich_colors: whether to show rich colors
expand: whether to expand the toast
@@ -172,10 +157,10 @@ class Toaster(Component):
class_name: The class name for the component.
autofocus: Whether the component should take the focus once the page is loaded
custom_attrs: custom attribute
- **props: The props of the component.
+ **props: The properties of the toaster.
Returns:
- The component.
+ The toaster component.
"""
...
@@ -189,7 +174,9 @@ class ToastNamespace(ComponentNamespace):
dismiss = staticmethod(Toaster.toast_dismiss)
@staticmethod
- def __call__(message: str, level: Optional[str], **props) -> "Optional[EventSpec]":
+ def __call__(
+ message: str = "", level: Optional[str] = None, **props
+ ) -> "Optional[EventSpec]":
"""Send a toast message.
Args:
@@ -197,6 +184,9 @@ class ToastNamespace(ComponentNamespace):
level: The level of the toast.
**props: The options for the toast.
+ Raises:
+ ValueError: If the Toaster component is not created.
+
Returns:
The toast event.
"""
diff --git a/reflex/components/suneditor/editor.py b/reflex/components/suneditor/editor.py
index 92a1e80c3..3bca8a3f6 100644
--- a/reflex/components/suneditor/editor.py
+++ b/reflex/components/suneditor/editor.py
@@ -1,15 +1,16 @@
"""A Rich Text Editor based on SunEditor."""
+
from __future__ import annotations
import enum
-from typing import Any, Dict, List, Literal, Optional, Union
+from typing import Dict, List, Literal, Optional, Tuple, Union
from reflex.base import Base
from reflex.components.component import Component, NoSSRComponent
-from reflex.constants import EventTriggers
+from reflex.event import EventHandler, empty_event, identity_event
from reflex.utils.format import to_camel_case
-from reflex.utils.imports import ImportVar
-from reflex.vars import Var
+from reflex.utils.imports import ImportDict, ImportVar
+from reflex.vars.base import Var
class EditorButtonList(list, enum.Enum):
@@ -67,6 +68,35 @@ class EditorOptions(Base):
button_list: Optional[List[Union[List[str], str]]]
+def on_blur_spec(e: Var, content: Var[str]) -> Tuple[Var[str]]:
+ """A helper function to specify the on_blur event handler.
+
+ Args:
+ e: The event.
+ content: The content of the editor.
+
+ Returns:
+ A tuple containing the content of the editor.
+ """
+ return (content,)
+
+
+def on_paste_spec(
+ e: Var, clean_data: Var[str], max_char_count: Var[bool]
+) -> Tuple[Var[str], Var[bool]]:
+ """A helper function to specify the on_paste event handler.
+
+ Args:
+ e: The event.
+ clean_data: The clean data.
+ max_char_count: The maximum character count.
+
+ Returns:
+ A tuple containing the clean data and the maximum character count.
+ """
+ return (clean_data, max_char_count)
+
+
class Editor(NoSSRComponent):
"""A Rich Text Editor component based on SunEditor.
Not every JS prop is listed here (some are not easily usable from python),
@@ -176,34 +206,41 @@ class Editor(NoSSRComponent):
# default: False
disable_toolbar: Var[bool]
- def _get_imports(self):
- imports = super()._get_imports()
- imports[""] = [
- ImportVar(tag="suneditor/dist/css/suneditor.min.css", install=False)
- ]
- return imports
+ # Fired when the editor content changes.
+ on_change: EventHandler[identity_event(str)]
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the event triggers that pass the component's value to the handler.
+ # Fired when the something is inputted in the editor.
+ on_input: EventHandler[empty_event]
+
+ # Fired when the editor loses focus.
+ on_blur: EventHandler[on_blur_spec]
+
+ # Fired when the editor is loaded.
+ on_load: EventHandler[identity_event(bool)]
+
+ # Fired when the editor content is copied.
+ on_copy: EventHandler[empty_event]
+
+ # Fired when the editor content is cut.
+ on_cut: EventHandler[empty_event]
+
+ # Fired when the editor content is pasted.
+ on_paste: EventHandler[on_paste_spec]
+
+ # Fired when the code view is toggled.
+ toggle_code_view: EventHandler[identity_event(bool)]
+
+ # Fired when the full screen mode is toggled.
+ toggle_full_screen: EventHandler[identity_event(bool)]
+
+ def add_imports(self) -> ImportDict:
+ """Add imports for the Editor component.
Returns:
- A dict mapping the event trigger to the var that is passed to the handler.
+ The import dict.
"""
return {
- **super().get_event_triggers(),
- EventTriggers.ON_CHANGE: lambda content: [content],
- "on_input": lambda _e: [_e],
- EventTriggers.ON_BLUR: lambda _e, content: [content],
- "on_load": lambda reload: [reload],
- "on_resize_editor": lambda height, prev_height: [height, prev_height],
- "on_copy": lambda _e, clipboard_data: [clipboard_data],
- "on_cut": lambda _e, clipboard_data: [clipboard_data],
- "on_paste": lambda _e, clean_data, max_char_count: [
- clean_data,
- max_char_count,
- ],
- "toggle_code_view": lambda is_code_view: [is_code_view],
- "toggle_full_screen": lambda is_full_screen: [is_full_screen],
+ "": ImportVar(tag="suneditor/dist/css/suneditor.min.css", install=False)
}
@classmethod
diff --git a/reflex/components/suneditor/editor.pyi b/reflex/components/suneditor/editor.pyi
index f878ef538..3734d2f16 100644
--- a/reflex/components/suneditor/editor.pyi
+++ b/reflex/components/suneditor/editor.pyi
@@ -1,20 +1,17 @@
"""Stub file for reflex/components/suneditor/editor.py"""
+
# ------------------- DO NOT EDIT ----------------------
# This file was generated by `reflex/utils/pyi_generator.py`!
# ------------------------------------------------------
-
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
import enum
-from typing import Any, Dict, List, Literal, Optional, Union
+from typing import Any, Dict, List, Literal, Optional, Tuple, Union, overload
+
from reflex.base import Base
-from reflex.components.component import Component, NoSSRComponent
-from reflex.constants import EventTriggers
-from reflex.utils.format import to_camel_case
-from reflex.utils.imports import ImportVar
-from reflex.vars import Var
+from reflex.components.component import NoSSRComponent
+from reflex.event import EventType
+from reflex.style import Style
+from reflex.utils.imports import ImportDict
+from reflex.vars.base import Var
class EditorButtonList(list, enum.Enum):
BASIC = [["font", "fontSize"], ["fontColor"], ["horizontalRule"], ["link", "image"]]
@@ -47,8 +44,13 @@ class EditorOptions(Base):
rtl: Optional[bool]
button_list: Optional[List[Union[List[str], str]]]
+def on_blur_spec(e: Var, content: Var[str]) -> Tuple[Var[str]]: ...
+def on_paste_spec(
+ e: Var, clean_data: Var[str], max_char_count: Var[bool]
+) -> Tuple[Var[str], Var[bool]]: ...
+
class Editor(NoSSRComponent):
- def get_event_triggers(self) -> Dict[str, Any]: ...
+ def add_imports(self) -> ImportDict: ...
@overload
@classmethod
def create( # type: ignore
@@ -56,54 +58,52 @@ class Editor(NoSSRComponent):
*children,
lang: Optional[
Union[
+ Literal[
+ "ckb",
+ "da",
+ "de",
+ "en",
+ "es",
+ "fr",
+ "he",
+ "it",
+ "ja",
+ "ko",
+ "lv",
+ "pl",
+ "pt_br",
+ "ro",
+ "ru",
+ "se",
+ "ua",
+ "zh_cn",
+ ],
Var[
Union[
Literal[
- "en",
+ "ckb",
"da",
"de",
+ "en",
"es",
"fr",
- "ja",
- "ko",
- "pt_br",
- "ru",
- "zh_cn",
- "ro",
- "pl",
- "ckb",
- "lv",
- "se",
- "ua",
"he",
"it",
+ "ja",
+ "ko",
+ "lv",
+ "pl",
+ "pt_br",
+ "ro",
+ "ru",
+ "se",
+ "ua",
+ "zh_cn",
],
dict,
]
],
- Union[
- Literal[
- "en",
- "da",
- "de",
- "es",
- "fr",
- "ja",
- "ko",
- "pt_br",
- "ru",
- "zh_cn",
- "ro",
- "pl",
- "ckb",
- "lv",
- "se",
- "ua",
- "he",
- "it",
- ],
- dict,
- ],
+ dict,
]
] = None,
name: Optional[Union[Var[str], str]] = None,
@@ -112,7 +112,7 @@ class Editor(NoSSRComponent):
height: Optional[Union[Var[str], str]] = None,
placeholder: Optional[Union[Var[str], str]] = None,
auto_focus: Optional[Union[Var[bool], bool]] = None,
- set_options: Optional[Union[Var[Dict], Dict]] = None,
+ set_options: Optional[Union[Dict, Var[Dict]]] = None,
set_all_plugins: Optional[Union[Var[bool], bool]] = None,
set_contents: Optional[Union[Var[str], str]] = None,
append_contents: Optional[Union[Var[str], str]] = None,
@@ -127,79 +127,30 @@ class Editor(NoSSRComponent):
class_name: Optional[Any] = None,
autofocus: Optional[bool] = None,
custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
- on_blur: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_change: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_context_menu: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_copy: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_cut: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_double_click: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_focus: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_input: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_load: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_down: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_enter: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_leave: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_move: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_out: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_over: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_mouse_up: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_paste: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_resize_editor: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_scroll: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- on_unmount: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- toggle_code_view: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- toggle_full_screen: Optional[
- Union[EventHandler, EventSpec, list, function, BaseVar]
- ] = None,
- **props
+ on_blur: Optional[EventType[str]] = None,
+ on_change: Optional[EventType[str]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_copy: Optional[EventType[[]]] = None,
+ on_cut: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_input: Optional[EventType[[]]] = None,
+ on_load: Optional[EventType[bool]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_paste: Optional[EventType[str, bool]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ toggle_code_view: Optional[EventType[bool]] = None,
+ toggle_full_screen: Optional[EventType[bool]] = None,
+ **props,
) -> "Editor":
"""Create an instance of Editor. No children allowed.
@@ -221,6 +172,15 @@ class Editor(NoSSRComponent):
hide: Hide the editor default: False
hide_toolbar: Hide the editor toolbar default: False
disable_toolbar: Disable the editor toolbar default: False
+ on_change: Fired when the editor content changes.
+ on_input: Fired when the something is inputted in the editor.
+ on_blur: Fired when the editor loses focus.
+ on_load: Fired when the editor is loaded.
+ on_copy: Fired when the editor content is copied.
+ on_cut: Fired when the editor content is cut.
+ on_paste: Fired when the editor content is pasted.
+ toggle_code_view: Fired when the code view is toggled.
+ toggle_full_screen: Fired when the full screen mode is toggled.
style: The style of the component.
key: A unique key for the component.
id: The id for the component.
diff --git a/reflex/components/tags/cond_tag.py b/reflex/components/tags/cond_tag.py
index 3143890c4..b4d0fe469 100644
--- a/reflex/components/tags/cond_tag.py
+++ b/reflex/components/tags/cond_tag.py
@@ -1,19 +1,21 @@
"""Tag to conditionally render components."""
+import dataclasses
from typing import Any, Dict, Optional
from reflex.components.tags.tag import Tag
-from reflex.vars import Var
+from reflex.vars.base import Var
+@dataclasses.dataclass()
class CondTag(Tag):
"""A conditional tag."""
# The condition to determine which component to render.
- cond: Var[Any]
+ cond: Var[Any] = dataclasses.field(default_factory=lambda: Var.create(True))
# The code to render if the condition is true.
- true_value: Dict
+ true_value: Dict = dataclasses.field(default_factory=dict)
# The code to render if the condition is false.
- false_value: Optional[Dict]
+ false_value: Optional[Dict] = None
diff --git a/reflex/components/tags/iter_tag.py b/reflex/components/tags/iter_tag.py
index 7ca050470..fec27f3d9 100644
--- a/reflex/components/tags/iter_tag.py
+++ b/reflex/components/tags/iter_tag.py
@@ -1,30 +1,44 @@
"""Tag to loop through a list of components."""
+
from __future__ import annotations
+import dataclasses
import inspect
-from typing import TYPE_CHECKING, Any, Callable, List, Tuple, Type, Union, get_args
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Iterable,
+ Tuple,
+ Type,
+ Union,
+ get_args,
+)
from reflex.components.tags.tag import Tag
-from reflex.vars import BaseVar, Var
+from reflex.vars import LiteralArrayVar, Var, get_unique_variable_name
if TYPE_CHECKING:
from reflex.components.component import Component
+@dataclasses.dataclass()
class IterTag(Tag):
"""An iterator tag."""
# The var to iterate over.
- iterable: Var[List]
+ iterable: Var[Iterable] = dataclasses.field(
+ default_factory=lambda: LiteralArrayVar.create([])
+ )
# The component render function for each item in the iterable.
- render_fn: Callable
+ render_fn: Callable = dataclasses.field(default_factory=lambda: lambda x: x)
# The name of the arg var.
- arg_var_name: str
+ arg_var_name: str = dataclasses.field(default_factory=get_unique_variable_name)
# The name of the index var.
- index_var_name: str
+ index_var_name: str = dataclasses.field(default_factory=get_unique_variable_name)
def get_iterable_var_type(self) -> Type:
"""Get the type of the iterable var.
@@ -32,15 +46,16 @@ class IterTag(Tag):
Returns:
The type of the iterable var.
"""
+ iterable = self.iterable
try:
- if self.iterable._var_type.mro()[0] == dict:
+ if iterable._var_type.mro()[0] is dict:
# Arg is a tuple of (key, value).
- return Tuple[get_args(self.iterable._var_type)] # type: ignore
- elif self.iterable._var_type.mro()[0] == tuple:
+ return Tuple[get_args(iterable._var_type)] # type: ignore
+ elif iterable._var_type.mro()[0] is tuple:
# Arg is a union of any possible values in the tuple.
- return Union[get_args(self.iterable._var_type)] # type: ignore
+ return Union[get_args(iterable._var_type)] # type: ignore
else:
- return get_args(self.iterable._var_type)[0]
+ return get_args(iterable._var_type)[0]
except Exception:
return Any
@@ -52,10 +67,10 @@ class IterTag(Tag):
Returns:
The index var.
"""
- return BaseVar(
- _var_name=self.index_var_name,
+ return Var(
+ _js_expr=self.index_var_name,
_var_type=int,
- )
+ ).guess_type()
def get_arg_var(self) -> Var:
"""Get the arg var for the tag (with curly braces).
@@ -65,10 +80,10 @@ class IterTag(Tag):
Returns:
The arg var.
"""
- return BaseVar(
- _var_name=self.arg_var_name,
+ return Var(
+ _js_expr=self.arg_var_name,
_var_type=self.get_iterable_var_type(),
- )
+ ).guess_type()
def get_index_var_arg(self) -> Var:
"""Get the index var for the tag (without curly braces).
@@ -78,11 +93,10 @@ class IterTag(Tag):
Returns:
The index var.
"""
- return BaseVar(
- _var_name=self.index_var_name,
+ return Var(
+ _js_expr=self.index_var_name,
_var_type=int,
- _var_is_local=True,
- )
+ ).guess_type()
def get_arg_var_arg(self) -> Var:
"""Get the arg var for the tag (without curly braces).
@@ -92,15 +106,17 @@ class IterTag(Tag):
Returns:
The arg var.
"""
- return BaseVar(
- _var_name=self.arg_var_name,
+ return Var(
+ _js_expr=self.arg_var_name,
_var_type=self.get_iterable_var_type(),
- _var_is_local=True,
- )
+ ).guess_type()
def render_component(self) -> Component:
"""Render the component.
+ Raises:
+ ValueError: If the render function takes more than 2 arguments.
+
Returns:
The rendered component.
"""
@@ -119,7 +135,8 @@ class IterTag(Tag):
component = self.render_fn(arg)
else:
# If the render function takes the index as an argument.
- assert len(args) == 2
+ if len(args) != 2:
+ raise ValueError("The render function must take 2 arguments.")
component = self.render_fn(arg, index)
# Nested foreach components or cond must be wrapped in fragments.
diff --git a/reflex/components/tags/match_tag.py b/reflex/components/tags/match_tag.py
index c2f6649d5..01eedb296 100644
--- a/reflex/components/tags/match_tag.py
+++ b/reflex/components/tags/match_tag.py
@@ -1,19 +1,21 @@
"""Tag to conditionally match cases."""
+import dataclasses
from typing import Any, List
from reflex.components.tags.tag import Tag
-from reflex.vars import Var
+from reflex.vars.base import Var
+@dataclasses.dataclass()
class MatchTag(Tag):
"""A match tag."""
# The condition to determine which case to match.
- cond: Var[Any]
+ cond: Var[Any] = dataclasses.field(default_factory=lambda: Var.create(True))
# The list of match cases to be matched.
- match_cases: List[Any]
+ match_cases: List[Any] = dataclasses.field(default_factory=list)
# The catchall case to match.
- default: Any
+ default: Any = dataclasses.field(default=Var.create(None))
diff --git a/reflex/components/tags/tag.py b/reflex/components/tags/tag.py
index 27b5dc7c1..0587c61ed 100644
--- a/reflex/components/tags/tag.py
+++ b/reflex/components/tags/tag.py
@@ -2,48 +2,40 @@
from __future__ import annotations
-from typing import Any, Dict, List, Optional, Set, Tuple, Union
+import dataclasses
+from typing import Any, Dict, List, Optional, Union
-from reflex.base import Base
from reflex.event import EventChain
from reflex.utils import format, types
-from reflex.vars import Var
+from reflex.vars.base import LiteralVar, Var
-class Tag(Base):
+@dataclasses.dataclass()
+class Tag:
"""A React tag."""
# The name of the tag.
name: str = ""
# The props of the tag.
- props: Dict[str, Any] = {}
+ props: Dict[str, Any] = dataclasses.field(default_factory=dict)
# The inner contents of the tag.
contents: str = ""
- # Args to pass to the tag.
- args: Optional[Tuple[str, ...]] = None
-
# Special props that aren't key value pairs.
- special_props: Set[Var] = set()
+ special_props: List[Var] = dataclasses.field(default_factory=list)
# The children components.
- children: List[Any] = []
+ children: List[Any] = dataclasses.field(default_factory=list)
- def __init__(self, *args, **kwargs):
- """Initialize the tag.
-
- Args:
- *args: Args to initialize the tag.
- **kwargs: Kwargs to initialize the tag.
- """
- # Convert any props to vars.
- if "props" in kwargs:
- kwargs["props"] = {
- name: Var.create(value) for name, value in kwargs["props"].items()
- }
- super().__init__(*args, **kwargs)
+ def __post_init__(self):
+ """Post initialize the tag."""
+ object.__setattr__(
+ self,
+ "props",
+ {name: LiteralVar.create(value) for name, value in self.props.items()},
+ )
def format_props(self) -> List:
"""Format the tag's props.
@@ -53,6 +45,29 @@ class Tag(Base):
"""
return format.format_props(*self.special_props, **self.props)
+ def set(self, **kwargs: Any):
+ """Set the tag's fields.
+
+ Args:
+ kwargs: The fields to set.
+
+ Returns:
+ The tag with the fields
+ """
+ for name, value in kwargs.items():
+ setattr(self, name, value)
+
+ return self
+
+ def __iter__(self):
+ """Iterate over the tag's fields.
+
+ Yields:
+ Tuple[str, Any]: The field name and value.
+ """
+ for field in dataclasses.fields(self):
+ yield field.name, getattr(self, field.name)
+
def add_props(self, **kwargs: Optional[Any]) -> Tag:
"""Add props to the tag.
@@ -62,14 +77,12 @@ class Tag(Base):
Returns:
The tag with the props added.
"""
- from reflex.components.core.colors import Color
-
self.props.update(
{
- format.to_camel_case(name, allow_hyphens=True): prop
- if types._isinstance(prop, Union[EventChain, dict])
- else Var.create(
- prop, _var_is_string=isinstance(prop, Color)
+ format.to_camel_case(name, allow_hyphens=True): (
+ prop
+ if types._isinstance(prop, Union[EventChain, dict])
+ else LiteralVar.create(prop)
) # rx.color is always a string
for name, prop in kwargs.items()
if self.is_valid_prop(prop)
diff --git a/reflex/config.py b/reflex/config.py
index 40c2ef8bf..12cc0916a 100644
--- a/reflex/config.py
+++ b/reflex/config.py
@@ -2,12 +2,21 @@
from __future__ import annotations
+import dataclasses
+import enum
import importlib
+import inspect
import os
import sys
import urllib.parse
+from pathlib import Path
from typing import Any, Dict, List, Optional, Set
+from typing_extensions import Annotated, get_type_hints
+
+from reflex.utils.exceptions import ConfigError, EnvironmentVarValueError
+from reflex.utils.types import GenericType, is_union, value_inside_optional
+
try:
import pydantic.v1 as pydantic
except ModuleNotFoundError:
@@ -128,6 +137,258 @@ class DBConfig(Base):
return f"{self.engine}://{path}/{self.database}"
+def get_default_value_for_field(field: dataclasses.Field) -> Any:
+ """Get the default value for a field.
+
+ Args:
+ field: The field.
+
+ Returns:
+ The default value.
+
+ Raises:
+ ValueError: If no default value is found.
+ """
+ if field.default != dataclasses.MISSING:
+ return field.default
+ elif field.default_factory != dataclasses.MISSING:
+ return field.default_factory()
+ else:
+ raise ValueError(
+ f"Missing value for environment variable {field.name} and no default value found"
+ )
+
+
+# TODO: Change all interpret_.* signatures to value: str, field: dataclasses.Field once we migrate rx.Config to dataclasses
+def interpret_boolean_env(value: str, field_name: str) -> bool:
+ """Interpret a boolean environment variable value.
+
+ Args:
+ value: The environment variable value.
+ field_name: The field name.
+
+ Returns:
+ The interpreted value.
+
+ Raises:
+ EnvironmentVarValueError: If the value is invalid.
+ """
+ true_values = ["true", "1", "yes", "y"]
+ false_values = ["false", "0", "no", "n"]
+
+ if value.lower() in true_values:
+ return True
+ elif value.lower() in false_values:
+ return False
+ raise EnvironmentVarValueError(f"Invalid boolean value: {value} for {field_name}")
+
+
+def interpret_int_env(value: str, field_name: str) -> int:
+ """Interpret an integer environment variable value.
+
+ Args:
+ value: The environment variable value.
+ field_name: The field name.
+
+ Returns:
+ The interpreted value.
+
+ Raises:
+ EnvironmentVarValueError: If the value is invalid.
+ """
+ try:
+ return int(value)
+ except ValueError as ve:
+ raise EnvironmentVarValueError(
+ f"Invalid integer value: {value} for {field_name}"
+ ) from ve
+
+
+def interpret_existing_path_env(value: str, field_name: str) -> ExistingPath:
+ """Interpret a path environment variable value as an existing path.
+
+ Args:
+ value: The environment variable value.
+ field_name: The field name.
+
+ Returns:
+ The interpreted value.
+
+ Raises:
+ EnvironmentVarValueError: If the path does not exist.
+ """
+ path = Path(value)
+ if not path.exists():
+ raise EnvironmentVarValueError(f"Path does not exist: {path} for {field_name}")
+ return path
+
+
+def interpret_path_env(value: str, field_name: str) -> Path:
+ """Interpret a path environment variable value.
+
+ Args:
+ value: The environment variable value.
+ field_name: The field name.
+
+ Returns:
+ The interpreted value.
+ """
+ return Path(value)
+
+
+def interpret_enum_env(value: str, field_type: GenericType, field_name: str) -> Any:
+ """Interpret an enum environment variable value.
+
+ Args:
+ value: The environment variable value.
+ field_type: The field type.
+ field_name: The field name.
+
+ Returns:
+ The interpreted value.
+
+ Raises:
+ EnvironmentVarValueError: If the value is invalid.
+ """
+ try:
+ return field_type(value)
+ except ValueError as ve:
+ raise EnvironmentVarValueError(
+ f"Invalid enum value: {value} for {field_name}"
+ ) from ve
+
+
+def interpret_env_var_value(
+ value: str, field_type: GenericType, field_name: str
+) -> Any:
+ """Interpret an environment variable value based on the field type.
+
+ Args:
+ value: The environment variable value.
+ field_type: The field type.
+ field_name: The field name.
+
+ Returns:
+ The interpreted value.
+
+ Raises:
+ ValueError: If the value is invalid.
+ """
+ field_type = value_inside_optional(field_type)
+
+ if is_union(field_type):
+ raise ValueError(
+ f"Union types are not supported for environment variables: {field_name}."
+ )
+
+ if field_type is bool:
+ return interpret_boolean_env(value, field_name)
+ elif field_type is str:
+ return value
+ elif field_type is int:
+ return interpret_int_env(value, field_name)
+ elif field_type is Path:
+ return interpret_path_env(value, field_name)
+ elif field_type is ExistingPath:
+ return interpret_existing_path_env(value, field_name)
+ elif inspect.isclass(field_type) and issubclass(field_type, enum.Enum):
+ return interpret_enum_env(value, field_type, field_name)
+
+ else:
+ raise ValueError(
+ f"Invalid type for environment variable {field_name}: {field_type}. This is probably an issue in Reflex."
+ )
+
+
+class PathExistsFlag:
+ """Flag to indicate that a path must exist."""
+
+
+ExistingPath = Annotated[Path, PathExistsFlag]
+
+
+@dataclasses.dataclass(init=False)
+class EnvironmentVariables:
+ """Environment variables class to instantiate environment variables."""
+
+ # Whether to use npm over bun to install frontend packages.
+ REFLEX_USE_NPM: bool = False
+
+ # The npm registry to use.
+ NPM_CONFIG_REGISTRY: Optional[str] = None
+
+ # Whether to use Granian for the backend. Otherwise, use Uvicorn.
+ REFLEX_USE_GRANIAN: bool = False
+
+ # The username to use for authentication on python package repository. Username and password must both be provided.
+ TWINE_USERNAME: Optional[str] = None
+
+ # The password to use for authentication on python package repository. Username and password must both be provided.
+ TWINE_PASSWORD: Optional[str] = None
+
+ # Whether to use the system installed bun. If set to false, bun will be bundled with the app.
+ REFLEX_USE_SYSTEM_BUN: bool = False
+
+ # Whether to use the system installed node and npm. If set to false, node and npm will be bundled with the app.
+ REFLEX_USE_SYSTEM_NODE: bool = False
+
+ # The working directory for the next.js commands.
+ REFLEX_WEB_WORKDIR: Path = Path(constants.Dirs.WEB)
+
+ # Path to the alembic config file
+ ALEMBIC_CONFIG: ExistingPath = Path(constants.ALEMBIC_CONFIG)
+
+ # Disable SSL verification for HTTPX requests.
+ SSL_NO_VERIFY: bool = False
+
+ # The directory to store uploaded files.
+ REFLEX_UPLOADED_FILES_DIR: Path = Path(constants.Dirs.UPLOADED_FILES)
+
+ # Whether to use seperate processes to compile the frontend and how many. If not set, defaults to thread executor.
+ REFLEX_COMPILE_PROCESSES: Optional[int] = None
+
+ # Whether to use seperate threads to compile the frontend and how many. Defaults to `min(32, os.cpu_count() + 4)`.
+ REFLEX_COMPILE_THREADS: Optional[int] = None
+
+ # The directory to store reflex dependencies.
+ REFLEX_DIR: Path = Path(constants.Reflex.DIR)
+
+ # Whether to print the SQL queries if the log level is INFO or lower.
+ SQLALCHEMY_ECHO: bool = False
+
+ # Whether to ignore the redis config error. Some redis servers only allow out-of-band configuration.
+ REFLEX_IGNORE_REDIS_CONFIG_ERROR: bool = False
+
+ # Whether to skip purging the web directory in dev mode.
+ REFLEX_PERSIST_WEB_DIR: bool = False
+
+ # The reflex.build frontend host.
+ REFLEX_BUILD_FRONTEND: str = constants.Templates.REFLEX_BUILD_FRONTEND
+
+ # The reflex.build backend host.
+ REFLEX_BUILD_BACKEND: str = constants.Templates.REFLEX_BUILD_BACKEND
+
+ def __init__(self):
+ """Initialize the environment variables."""
+ type_hints = get_type_hints(type(self))
+
+ for field in dataclasses.fields(self):
+ raw_value = os.getenv(field.name, None)
+
+ field.type = type_hints.get(field.name) or field.type
+
+ value = (
+ interpret_env_var_value(raw_value, field.type, field.name)
+ if raw_value is not None
+ else get_default_value_for_field(field)
+ )
+
+ setattr(self, field.name, value)
+
+
+environment = EnvironmentVariables()
+
+
class Config(Base):
"""The config defines runtime settings for the app.
@@ -158,16 +419,16 @@ class Config(Base):
app_name: str
# The log level to use.
- loglevel: constants.LogLevel = constants.LogLevel.INFO
+ loglevel: constants.LogLevel = constants.LogLevel.DEFAULT
# The port to run the frontend on. NOTE: When running in dev mode, the next available port will be used if this is taken.
- frontend_port: int = 3000
+ frontend_port: int = constants.DefaultPorts.FRONTEND_PORT
# The path to run the frontend on. For example, "/app" will run the frontend on http://localhost:3000/app
frontend_path: str = ""
# The port to run the backend on. NOTE: When running in dev mode, the next available port will be used if this is taken.
- backend_port: int = 8000
+ backend_port: int = constants.DefaultPorts.BACKEND_PORT
# The backend url the frontend will connect to. This must be updated if the backend is hosted elsewhere, or in production.
api_url: str = f"http://localhost:{backend_port}"
@@ -188,13 +449,16 @@ class Config(Base):
telemetry_enabled: bool = True
# The bun path
- bun_path: str = constants.Bun.DEFAULT_PATH
+ bun_path: ExistingPath = constants.Bun.DEFAULT_PATH
+
+ # Timeout to do a production build of a frontend page.
+ static_page_generation_timeout: int = 60
# List of origins that are allowed to connect to the backend API.
cors_allowed_origins: List[str] = ["*"]
# Tailwind config.
- tailwind: Optional[Dict[str, Any]] = {}
+ tailwind: Optional[Dict[str, Any]] = {"plugins": ["@tailwindcss/typography"]}
# Timeout when launching the gunicorn server. TODO(rename this to backend_timeout?)
timeout: int = 120
@@ -202,6 +466,9 @@ class Config(Base):
# Whether to enable or disable nextJS gzip compression.
next_compression: bool = True
+ # Whether to use React strict mode in nextJS
+ react_strict_mode: bool = True
+
# Additional frontend packages to install.
frontend_packages: List[str] = []
@@ -213,15 +480,39 @@ class Config(Base):
# The worker class used in production mode
gunicorn_worker_class: str = "uvicorn.workers.UvicornH11Worker"
+ # Number of gunicorn workers from user
+ gunicorn_workers: Optional[int] = None
+
+ # Number of requests before a worker is restarted
+ gunicorn_max_requests: int = 100
+
+ # Variance limit for max requests; gunicorn only
+ gunicorn_max_requests_jitter: int = 25
+
+ # Indicate which type of state manager to use
+ state_manager_mode: constants.StateManagerMode = constants.StateManagerMode.DISK
+
+ # Maximum expiration lock time for redis state manager
+ redis_lock_expiration: int = constants.Expiration.LOCK
+
+ # Token expiration time for redis state manager
+ redis_token_expiration: int = constants.Expiration.TOKEN
+
# Attributes that were explicitly set by the user.
_non_default_attributes: Set[str] = pydantic.PrivateAttr(set())
+ # Path to file containing key-values pairs to override in the environment; Dotenv format.
+ env_file: Optional[str] = None
+
def __init__(self, *args, **kwargs):
"""Initialize the config values.
Args:
*args: The args to pass to the Pydantic init method.
**kwargs: The kwargs to pass to the Pydantic init method.
+
+ Raises:
+ ConfigError: If some values in the config are invalid.
"""
super().__init__(*args, **kwargs)
@@ -235,6 +526,14 @@ class Config(Base):
self._non_default_attributes.update(kwargs)
self._replace_defaults(**kwargs)
+ if (
+ self.state_manager_mode == constants.StateManagerMode.REDIS
+ and not self.redis_url
+ ):
+ raise ConfigError(
+ "REDIS_URL is required when using the redis state manager."
+ )
+
@property
def module(self) -> str:
"""Get the module name of the app.
@@ -246,14 +545,21 @@ class Config(Base):
def update_from_env(self) -> dict[str, Any]:
"""Update the config values based on set environment variables.
+ If there is a set env_file, it is loaded first.
Returns:
The updated config values.
-
- Raises:
- EnvVarValueError: If an environment variable is set to an invalid type.
"""
- from reflex.utils.exceptions import EnvVarValueError
+ if self.env_file:
+ try:
+ from dotenv import load_dotenv # type: ignore
+
+ # load env file if exists
+ load_dotenv(self.env_file, override=True)
+ except ImportError:
+ console.error(
+ """The `python-dotenv` package is required to load environment variables from a file. Run `pip install "python-dotenv>=1.0.1"`."""
+ )
updated_values = {}
# Iterate over the fields.
@@ -265,24 +571,15 @@ class Config(Base):
if env_var is not None:
if key.upper() != "DB_URL":
console.info(
- f"Overriding config value {key} with env var {key.upper()}={env_var}"
+ f"Overriding config value {key} with env var {key.upper()}={env_var}",
+ dedupe=True,
)
- # Convert the env var to the expected type.
- try:
- if issubclass(field.type_, bool):
- # special handling for bool values
- env_var = env_var.lower() in ["true", "1", "yes"]
- else:
- env_var = field.type_(env_var)
- except ValueError as ve:
- console.error(
- f"Could not convert {key.upper()}={env_var} to type {field.type_}"
- )
- raise EnvVarValueError from ve
+ # Interpret the value.
+ value = interpret_env_var_value(env_var, field.outer_type_, field.name)
# Set the value.
- updated_values[key] = env_var
+ updated_values[key] = value
return updated_values
@@ -310,17 +607,22 @@ class Config(Base):
):
self.deploy_url = f"http://localhost:{kwargs['frontend_port']}"
- # If running in Github Codespaces, override API_URL
- codespace_name = os.getenv("CODESPACE_NAME")
- if "api_url" not in self._non_default_attributes and codespace_name:
+ if "api_url" not in self._non_default_attributes:
+ # If running in Github Codespaces, override API_URL
+ codespace_name = os.getenv("CODESPACE_NAME")
GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN = os.getenv(
"GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN"
)
- if codespace_name:
+ # If running on Replit.com interactively, override API_URL to ensure we maintain the backend_port
+ replit_dev_domain = os.getenv("REPLIT_DEV_DOMAIN")
+ backend_port = kwargs.get("backend_port", self.backend_port)
+ if codespace_name and GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN:
self.api_url = (
f"https://{codespace_name}-{kwargs.get('backend_port', self.backend_port)}"
f".{GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN}"
)
+ elif replit_dev_domain and backend_port:
+ self.api_url = f"https://{replit_dev_domain}:{backend_port}"
def _set_persistent(self, **kwargs):
"""Set values in this config and in the environment so they persist into subprocess.
@@ -346,11 +648,14 @@ def get_config(reload: bool = False) -> Config:
The app config.
"""
sys.path.insert(0, os.getcwd())
- try:
- rxconfig = __import__(constants.Config.MODULE)
- if reload:
- importlib.reload(rxconfig)
- return rxconfig.config
-
- except ImportError:
- return Config(app_name="") # type: ignore
+ # only import the module if it exists. If a module spec exists then
+ # the module exists.
+ spec = importlib.util.find_spec(constants.Config.MODULE) # type: ignore
+ if not spec:
+ # we need this condition to ensure that a ModuleNotFound error is not thrown when
+ # running unit/integration tests.
+ return Config(app_name="")
+ rxconfig = importlib.import_module(constants.Config.MODULE)
+ if reload:
+ importlib.reload(rxconfig)
+ return rxconfig.config
diff --git a/reflex/config.pyi b/reflex/config.pyi
deleted file mode 100644
index 57ce1123d..000000000
--- a/reflex/config.pyi
+++ /dev/null
@@ -1,110 +0,0 @@
-""" Generated with stubgen from mypy, then manually edited, do not regen."""
-
-from reflex import constants as constants
-from reflex.base import Base as Base
-from reflex.utils import console as console
-from typing import Any, Dict, List, Optional, overload
-
-class DBConfig(Base):
- engine: str
- username: Optional[str]
- password: Optional[str]
- host: Optional[str]
- port: Optional[int]
- database: str
-
- def __init__(
- self,
- database: str,
- engine: str,
- username: Optional[str] = None,
- password: Optional[str] = None,
- host: Optional[str] = None,
- port: Optional[int] = None,
- ): ...
- @classmethod
- def postgresql(
- cls,
- database: str,
- username: str,
- password: str | None = ...,
- host: str | None = ...,
- port: int | None = ...,
- ) -> DBConfig: ...
- @classmethod
- def postgresql_psycopg2(
- cls,
- database: str,
- username: str,
- password: str | None = ...,
- host: str | None = ...,
- port: int | None = ...,
- ) -> DBConfig: ...
- @classmethod
- def sqlite(cls, database: str) -> DBConfig: ...
- def get_url(self) -> str: ...
-
-class Config(Base):
- class Config:
- validate_assignment: bool
- app_name: str
- loglevel: constants.LogLevel
- frontend_port: int
- frontend_path: str
- backend_port: int
- api_url: str
- deploy_url: Optional[str]
- backend_host: str
- db_url: Optional[str]
- redis_url: Optional[str]
- telemetry_enabled: bool
- bun_path: str
- cors_allowed_origins: List[str]
- tailwind: Optional[Dict[str, Any]]
- timeout: int
- next_compression: bool
- event_namespace: Optional[str]
- frontend_packages: List[str]
- rxdeploy_url: Optional[str]
- cp_backend_url: str
- cp_web_url: str
- username: Optional[str]
- gunicorn_worker_class: str
-
- def __init__(
- self,
- *args,
- app_name: str,
- loglevel: Optional[constants.LogLevel] = None,
- frontend_port: Optional[int] = None,
- frontend_path: Optional[str] = None,
- backend_port: Optional[int] = None,
- api_url: Optional[str] = None,
- deploy_url: Optional[str] = None,
- backend_host: Optional[str] = None,
- db_url: Optional[str] = None,
- redis_url: Optional[str] = None,
- telemetry_enabled: Optional[bool] = None,
- bun_path: Optional[str] = None,
- cors_allowed_origins: Optional[List[str]] = None,
- tailwind: Optional[Dict[str, Any]] = None,
- timeout: Optional[int] = None,
- next_compression: Optional[bool] = None,
- event_namespace: Optional[str] = None,
- frontend_packages: Optional[List[str]] = None,
- rxdeploy_url: Optional[str] = None,
- cp_backend_url: Optional[str] = None,
- cp_web_url: Optional[str] = None,
- username: Optional[str] = None,
- gunicorn_worker_class: Optional[str] = None,
- **kwargs
- ) -> None: ...
- @property
- def module(self) -> str: ...
- @staticmethod
- def check_deprecated_values(**kwargs) -> None: ...
- def update_from_env(self) -> None: ...
- def get_event_namespace(self) -> str: ...
- def _set_persistent(self, **kwargs) -> None: ...
-
-def get_config(reload: bool = ...) -> Config: ...
diff --git a/reflex/constants/__init__.py b/reflex/constants/__init__.py
index 1f3325a8a..a540805b5 100644
--- a/reflex/constants/__init__.py
+++ b/reflex/constants/__init__.py
@@ -2,6 +2,8 @@
from .base import (
COOKIES,
+ ENV_BACKEND_ONLY_ENV_VAR,
+ ENV_FRONTEND_ONLY_ENV_VAR,
ENV_MODE_ENV_VAR,
IS_WINDOWS,
LOCAL_STORAGE,
@@ -10,6 +12,7 @@ from .base import (
REFLEX_VAR_CLOSING_TAG,
REFLEX_VAR_OPENING_TAG,
RELOAD_CONFIG,
+ SESSION_STORAGE,
SKIP_COMPILE_ENV_VAR,
ColorMode,
Dirs,
@@ -35,8 +38,8 @@ from .compiler import (
)
from .config import (
ALEMBIC_CONFIG,
- PRODUCTION_BACKEND_URL,
Config,
+ DefaultPorts,
Expiration,
GitIgnore,
RequirementsTxt,
@@ -62,7 +65,8 @@ from .route import (
RouteRegex,
RouteVar,
)
-from .style import STYLES_DIR, Tailwind
+from .state import StateManagerMode
+from .style import Tailwind
__ALL__ = [
ALEMBIC_CONFIG,
@@ -73,6 +77,7 @@ __ALL__ = [
ComponentName,
CustomComponents,
DefaultPage,
+ DefaultPorts,
Dirs,
Endpoint,
Env,
@@ -87,6 +92,7 @@ __ALL__ = [
Imports,
IS_WINDOWS,
LOCAL_STORAGE,
+ SESSION_STORAGE,
LogLevel,
MemoizationDisposition,
MemoizationMode,
@@ -99,7 +105,6 @@ __ALL__ = [
Ping,
POLLING_MAX_HTTP_BUFFER_SIZE,
PYTEST_CURRENT_TEST,
- PRODUCTION_BACKEND_URL,
Reflex,
RELOAD_CONFIG,
RequirementsTxt,
@@ -113,7 +118,7 @@ __ALL__ = [
SETTER_PREFIX,
SKIP_COMPILE_ENV_VAR,
SocketEvent,
- STYLES_DIR,
+ StateManagerMode,
Tailwind,
Templates,
CompileVars,
diff --git a/reflex/constants/base.py b/reflex/constants/base.py
index 733859ad4..bba53d625 100644
--- a/reflex/constants/base.py
+++ b/reflex/constants/base.py
@@ -2,14 +2,16 @@
from __future__ import annotations
-import os
import platform
from enum import Enum
from importlib import metadata
+from pathlib import Path
from types import SimpleNamespace
from platformdirs import PlatformDirs
+from .utils import classproperty
+
IS_WINDOWS = platform.system() == "Windows"
@@ -19,32 +21,36 @@ class Dirs(SimpleNamespace):
# The frontend directories in a project.
# The web folder where the NextJS app is compiled to.
WEB = ".web"
+ # The directory where uploaded files are stored.
+ UPLOADED_FILES = "uploaded_files"
# The name of the assets directory.
APP_ASSETS = "assets"
+ # The name of the assets directory for external ressource (a subfolder of APP_ASSETS).
+ EXTERNAL_APP_ASSETS = "external"
# The name of the utils file.
UTILS = "utils"
- # The name of the output static directory.
- STATIC = "_static"
# The name of the state file.
STATE_PATH = "/".join([UTILS, "state"])
# The name of the components file.
COMPONENTS_PATH = "/".join([UTILS, "components"])
# The name of the contexts file.
CONTEXTS_PATH = "/".join([UTILS, "context"])
- # The directory where the app pages are compiled to.
- WEB_PAGES = os.path.join(WEB, "pages")
- # The directory where the static build is located.
- WEB_STATIC = os.path.join(WEB, STATIC)
- # The directory where the utils file is located.
- WEB_UTILS = os.path.join(WEB, UTILS)
- # The directory where the assets are located.
- WEB_ASSETS = os.path.join(WEB, "public")
- # The env json file.
- ENV_JSON = os.path.join(WEB, "env.json")
- # The reflex json file.
- REFLEX_JSON = os.path.join(WEB, "reflex.json")
- # The path to postcss.config.js
- POSTCSS_JS = os.path.join(WEB, "postcss.config.js")
+ # The name of the output static directory.
+ STATIC = "_static"
+ # The name of the public html directory served at "/"
+ PUBLIC = "public"
+ # The directory where styles are located.
+ STYLES = "styles"
+ # The name of the pages directory.
+ PAGES = "pages"
+ # The name of the env json file.
+ ENV_JSON = "env.json"
+ # The name of the reflex json file.
+ REFLEX_JSON = "reflex.json"
+ # The name of the postcss config file.
+ POSTCSS_JS = "postcss.config.js"
+ # The name of the states directory.
+ STATES = "states"
class Reflex(SimpleNamespace):
@@ -57,25 +63,20 @@ class Reflex(SimpleNamespace):
VERSION = metadata.version(MODULE_NAME)
# The reflex json file.
- JSON = os.path.join(Dirs.WEB, "reflex.json")
+ JSON = "reflex.json"
# Files and directories used to init a new project.
# The directory to store reflex dependencies.
- # Get directory value from enviroment variables if it exists.
- _dir = os.environ.get("REFLEX_DIR", "")
+ # on windows, we use C:/Users//AppData/Local/reflex.
+ # on macOS, we use ~/Library/Application Support/reflex.
+ # on linux, we use ~/.local/share/reflex.
+ # If user sets REFLEX_DIR envroment variable use that instead.
+ DIR = PlatformDirs(MODULE_NAME, False).user_data_path
- DIR = _dir or (
- # on windows, we use C:/Users//AppData/Local/reflex.
- # on macOS, we use ~/Library/Application Support/reflex.
- # on linux, we use ~/.local/share/reflex.
- # If user sets REFLEX_DIR envroment variable use that instead.
- PlatformDirs(MODULE_NAME, False).user_data_dir
- )
# The root directory of the reflex library.
+ ROOT_DIR = Path(__file__).parents[2]
- ROOT_DIR = os.path.dirname(
- os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
- )
+ RELEASES_URL = f"https://api.github.com/repos/reflex-dev/templates/releases"
class ReflexHostingCLI(SimpleNamespace):
@@ -94,15 +95,62 @@ class Templates(SimpleNamespace):
# The default template
DEFAULT = "blank"
+ # The reflex.build frontend host
+ REFLEX_BUILD_FRONTEND = "https://flexgen.reflex.run"
+
+ # The reflex.build backend host
+ REFLEX_BUILD_BACKEND = "https://flexgen-prod-flexgen.fly.dev"
+
+ @classproperty
+ @classmethod
+ def REFLEX_BUILD_URL(cls):
+ """The URL to redirect to reflex.build.
+
+ Returns:
+ The URL to redirect to reflex.build.
+ """
+ from reflex.config import environment
+
+ return (
+ environment.REFLEX_BUILD_FRONTEND
+ + "/gen?reflex_init_token={reflex_init_token}"
+ )
+
+ @classproperty
+ @classmethod
+ def REFLEX_BUILD_POLL_URL(cls):
+ """The URL to poll waiting for the user to select a generation.
+
+ Returns:
+ The URL to poll waiting for the user to select a generation.
+ """
+ from reflex.config import environment
+
+ return environment.REFLEX_BUILD_BACKEND + "/api/init/{reflex_init_token}"
+
+ @classproperty
+ @classmethod
+ def REFLEX_BUILD_CODE_URL(cls):
+ """The URL to fetch the generation's reflex code.
+
+ Returns:
+ The URL to fetch the generation's reflex code.
+ """
+ from reflex.config import environment
+
+ return (
+ environment.REFLEX_BUILD_BACKEND + "/api/gen/{generation_hash}/refactored"
+ )
+
class Dirs(SimpleNamespace):
"""Folders used by the template system of Reflex."""
# The template directory used during reflex init.
- BASE = os.path.join(Reflex.ROOT_DIR, Reflex.MODULE_NAME, ".templates")
+ BASE = Reflex.ROOT_DIR / Reflex.MODULE_NAME / ".templates"
# The web subdirectory of the template directory.
- WEB_TEMPLATE = os.path.join(BASE, "web")
+ WEB_TEMPLATE = BASE / "web"
# The jinja template directory.
- JINJA_TEMPLATE = os.path.join(BASE, "jinja")
+ JINJA_TEMPLATE = BASE / "jinja"
# Where the code for the templates is stored.
CODE = "code"
@@ -113,7 +161,7 @@ class Next(SimpleNamespace):
# The NextJS config file
CONFIG_FILE = "next.config.js"
# The sitemap config file.
- SITEMAP_CONFIG_FILE = os.path.join(Dirs.WEB, "next-sitemap.config.js")
+ SITEMAP_CONFIG_FILE = "next-sitemap.config.js"
# The node modules directory.
NODE_MODULES = "node_modules"
# The package lock file.
@@ -126,9 +174,11 @@ class Next(SimpleNamespace):
class ColorMode(SimpleNamespace):
"""Constants related to ColorMode."""
- NAME = "colorMode"
+ NAME = "rawColorMode"
+ RESOLVED_NAME = "resolvedColorMode"
USE = "useColorMode"
TOGGLE = "toggleColorMode"
+ SET = "setColorMode"
# Env modes
@@ -144,6 +194,7 @@ class LogLevel(str, Enum):
"""The log levels."""
DEBUG = "debug"
+ DEFAULT = "default"
INFO = "info"
WARNING = "warning"
ERROR = "error"
@@ -161,6 +212,14 @@ class LogLevel(str, Enum):
levels = list(LogLevel)
return levels.index(self) <= levels.index(other)
+ def subprocess_level(self):
+ """Return the log level for the subprocess.
+
+ Returns:
+ The log level for the subprocess
+ """
+ return self if self != LogLevel.DEFAULT else LogLevel.WARNING
+
# Server socket configuration variables
POLLING_MAX_HTTP_BUFFER_SIZE = 1000 * 1000
@@ -178,6 +237,7 @@ class Ping(SimpleNamespace):
# Keys in the client_side_storage dict
COOKIES = "cookies"
LOCAL_STORAGE = "local_storage"
+SESSION_STORAGE = "session_storage"
# If this env var is set to "yes", App.compile will be a no-op
SKIP_COMPILE_ENV_VAR = "__REFLEX_SKIP_COMPILE"
@@ -185,6 +245,9 @@ SKIP_COMPILE_ENV_VAR = "__REFLEX_SKIP_COMPILE"
# This env var stores the execution mode of the app
ENV_MODE_ENV_VAR = "REFLEX_ENV_MODE"
+ENV_BACKEND_ONLY_ENV_VAR = "REFLEX_BACKEND_ONLY"
+ENV_FRONTEND_ONLY_ENV_VAR = "REFLEX_FRONTEND_ONLY"
+
# Testing variables.
# Testing os env set by pytest when running a test case.
PYTEST_CURRENT_TEST = "PYTEST_CURRENT_TEST"
diff --git a/reflex/constants/base.pyi b/reflex/constants/base.pyi
deleted file mode 100644
index 90804a080..000000000
--- a/reflex/constants/base.pyi
+++ /dev/null
@@ -1,94 +0,0 @@
-"""Stub file for reflex/constants/base.py"""
-# ------------------- DO NOT EDIT ----------------------
-# This file was generated by `reflex/utils/pyi_generator.py`!
-# ------------------------------------------------------
-
-from typing import Any, Dict, Literal, Optional, Union, overload
-from reflex.vars import Var, BaseVar, ComputedVar
-from reflex.event import EventChain, EventHandler, EventSpec
-from reflex.style import Style
-import os
-import platform
-from enum import Enum
-from importlib import metadata
-from types import SimpleNamespace
-from platformdirs import PlatformDirs
-
-IS_WINDOWS = platform.system() == "Windows"
-
-class Dirs(SimpleNamespace):
- WEB = ".web"
- APP_ASSETS = "assets"
- UTILS = "utils"
- STATIC = "_static"
- STATE_PATH = "/".join([UTILS, "state"])
- COMPONENTS_PATH = "/".join([UTILS, "components"])
- CONTEXTS_PATH = "/".join([UTILS, "context"])
- WEB_PAGES = os.path.join(WEB, "pages")
- WEB_STATIC = os.path.join(WEB, STATIC)
- WEB_UTILS = os.path.join(WEB, UTILS)
- WEB_ASSETS = os.path.join(WEB, "public")
- ENV_JSON = os.path.join(WEB, "env.json")
- REFLEX_JSON = os.path.join(WEB, "reflex.json")
- POSTCSS_JS = os.path.join(WEB, "postcss.config.js")
-
-class Reflex(SimpleNamespace):
- MODULE_NAME = "reflex"
- VERSION = metadata.version(MODULE_NAME)
- JSON = os.path.join(Dirs.WEB, "reflex.json")
- _dir = os.environ.get("REFLEX_DIR", "")
- DIR = _dir or PlatformDirs(MODULE_NAME, False).user_data_dir
- ROOT_DIR = os.path.dirname(
- os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
- )
-
-class ReflexHostingCLI(SimpleNamespace):
- MODULE_NAME = "reflex-hosting-cli"
-
-class Templates(SimpleNamespace):
- APP_TEMPLATES_ROUTE = "/app-templates"
- DEFAULT = "blank"
-
- class Dirs(SimpleNamespace):
- BASE = os.path.join(Reflex.ROOT_DIR, Reflex.MODULE_NAME, ".templates")
- WEB_TEMPLATE = os.path.join(BASE, "web")
- JINJA_TEMPLATE = os.path.join(BASE, "jinja")
- CODE = "code"
-
-class Next(SimpleNamespace):
- CONFIG_FILE = "next.config.js"
- SITEMAP_CONFIG_FILE = os.path.join(Dirs.WEB, "next-sitemap.config.js")
- NODE_MODULES = "node_modules"
- PACKAGE_LOCK = "package-lock.json"
- FRONTEND_LISTENING_REGEX = "Local:[\\s]+(.*)"
-
-class ColorMode(SimpleNamespace):
- NAME = "colorMode"
- USE = "useColorMode"
- TOGGLE = "toggleColorMode"
-
-class Env(str, Enum):
- DEV = "dev"
- PROD = "prod"
-
-class LogLevel(str, Enum):
- DEBUG = "debug"
- INFO = "info"
- WARNING = "warning"
- ERROR = "error"
- CRITICAL = "critical"
-
-POLLING_MAX_HTTP_BUFFER_SIZE = 1000 * 1000
-
-class Ping(SimpleNamespace):
- INTERVAL = 25
- TIMEOUT = 120
-
-COOKIES = "cookies"
-LOCAL_STORAGE = "local_storage"
-SKIP_COMPILE_ENV_VAR = "__REFLEX_SKIP_COMPILE"
-ENV_MODE_ENV_VAR = "REFLEX_ENV_MODE"
-PYTEST_CURRENT_TEST = "PYTEST_CURRENT_TEST"
-RELOAD_CONFIG = "__REFLEX_RELOAD_CONFIG"
-REFLEX_VAR_OPENING_TAG = ""
-REFLEX_VAR_CLOSING_TAG = " "
diff --git a/reflex/constants/colors.py b/reflex/constants/colors.py
index ddd093f25..60942c775 100644
--- a/reflex/constants/colors.py
+++ b/reflex/constants/colors.py
@@ -35,7 +35,6 @@ ColorType = Literal[
"amber",
"gold",
"bronze",
- "gray",
"accent",
"black",
"white",
diff --git a/reflex/constants/compiler.py b/reflex/constants/compiler.py
index b99e31e8c..b7ffef161 100644
--- a/reflex/constants/compiler.py
+++ b/reflex/constants/compiler.py
@@ -12,7 +12,7 @@ from reflex.utils.imports import ImportVar
SETTER_PREFIX = "set_"
# The file used to specify no compilation.
-NOCOMPILE_FILE = ".web/nocompile"
+NOCOMPILE_FILE = "nocompile"
class Ext(SimpleNamespace):
@@ -62,9 +62,17 @@ class CompileVars(SimpleNamespace):
# The name of the function for converting a dict to an event.
TO_EVENT = "Event"
# The name of the internal on_load event.
- ON_LOAD_INTERNAL = "on_load_internal_state.on_load_internal"
+ ON_LOAD_INTERNAL = "reflex___state____on_load_internal_state.on_load_internal"
# The name of the internal event to update generic state vars.
- UPDATE_VARS_INTERNAL = "update_vars_internal_state.update_vars_internal"
+ UPDATE_VARS_INTERNAL = (
+ "reflex___state____update_vars_internal_state.update_vars_internal"
+ )
+ # The name of the frontend event exception state
+ FRONTEND_EXCEPTION_STATE = "reflex___state____frontend_event_exception_state"
+ # The full name of the frontend exception state
+ FRONTEND_EXCEPTION_STATE_FULL = (
+ f"reflex___state____state.{FRONTEND_EXCEPTION_STATE}"
+ )
class PageNames(SimpleNamespace):
@@ -80,6 +88,8 @@ class PageNames(SimpleNamespace):
DOCUMENT_ROOT = "_document"
# The name of the theme page.
THEME = "theme"
+ # The module containing components.
+ COMPONENTS = "components"
# The module containing shared stateful components
STATEFUL_COMPONENTS = "stateful_components"
@@ -103,9 +113,9 @@ class Imports(SimpleNamespace):
"""Common sets of import vars."""
EVENTS = {
- "react": {ImportVar(tag="useContext")},
- f"/{Dirs.CONTEXTS_PATH}": {ImportVar(tag="EventLoopContext")},
- f"/{Dirs.STATE_PATH}": {ImportVar(tag=CompileVars.TO_EVENT)},
+ "react": [ImportVar(tag="useContext")],
+ f"$/{Dirs.CONTEXTS_PATH}": [ImportVar(tag="EventLoopContext")],
+ f"$/{Dirs.STATE_PATH}": [ImportVar(tag=CompileVars.TO_EVENT)],
}
@@ -140,3 +150,28 @@ class MemoizationMode(Base):
# Whether children of this component should be memoized first.
recursive: bool = True
+
+
+class SpecialAttributes(enum.Enum):
+ """Special attributes for components.
+
+ These are placed in custom_attrs and rendered as-is rather than converting
+ to a style prop.
+ """
+
+ DATA_UNDERSCORE = "data_"
+ DATA_DASH = "data-"
+ ARIA_UNDERSCORE = "aria_"
+ ARIA_DASH = "aria-"
+
+ @classmethod
+ def is_special(cls, attr: str) -> bool:
+ """Check if the attribute is special.
+
+ Args:
+ attr: the attribute to check
+
+ Returns:
+ True if the attribute is special.
+ """
+ return any(attr.startswith(value.value) for value in cls)
diff --git a/reflex/constants/config.py b/reflex/constants/config.py
index 298934202..970e67844 100644
--- a/reflex/constants/config.py
+++ b/reflex/constants/config.py
@@ -1,5 +1,6 @@
"""Config constants."""
-import os
+
+from pathlib import Path
from types import SimpleNamespace
from reflex.constants.base import Dirs, Reflex
@@ -7,7 +8,7 @@ from reflex.constants.base import Dirs, Reflex
from .compiler import Ext
# Alembic migrations
-ALEMBIC_CONFIG = os.environ.get("ALEMBIC_CONFIG", "alembic.ini")
+ALEMBIC_CONFIG = "alembic.ini"
class Config(SimpleNamespace):
@@ -16,9 +17,7 @@ class Config(SimpleNamespace):
# The name of the reflex config module.
MODULE = "rxconfig"
# The python config file.
- FILE = f"{MODULE}{Ext.PY}"
- # The previous config file.
- PREVIOUS_FILE = f"pcconfig{Ext.PY}"
+ FILE = Path(f"{MODULE}{Ext.PY}")
class Expiration(SimpleNamespace):
@@ -36,9 +35,9 @@ class GitIgnore(SimpleNamespace):
"""Gitignore constants."""
# The gitignore file.
- FILE = ".gitignore"
+ FILE = Path(".gitignore")
# Files to gitignore.
- DEFAULTS = {Dirs.WEB, "*.db", "__pycache__/", "*.py[cod]"}
+ DEFAULTS = {Dirs.WEB, "*.db", "__pycache__/", "*.py[cod]", "assets/external/"}
class RequirementsTxt(SimpleNamespace):
@@ -50,5 +49,12 @@ class RequirementsTxt(SimpleNamespace):
DEFAULTS_STUB = f"{Reflex.MODULE_NAME}=="
+class DefaultPorts(SimpleNamespace):
+ """Default port constants."""
+
+ FRONTEND_PORT = 3000
+ BACKEND_PORT = 8000
+
+
# The deployment URL.
PRODUCTION_BACKEND_URL = "https://{username}-{app_name}.api.pynecone.app"
diff --git a/reflex/constants/custom_components.py b/reflex/constants/custom_components.py
index 3ea9cf6ed..d879a01f2 100644
--- a/reflex/constants/custom_components.py
+++ b/reflex/constants/custom_components.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+from pathlib import Path
from types import SimpleNamespace
@@ -11,9 +12,9 @@ class CustomComponents(SimpleNamespace):
# The name of the custom components source directory.
SRC_DIR = "custom_components"
# The name of the custom components pyproject.toml file.
- PYPROJECT_TOML = "pyproject.toml"
+ PYPROJECT_TOML = Path("pyproject.toml")
# The name of the custom components package README file.
- PACKAGE_README = "README.md"
+ PACKAGE_README = Path("README.md")
# The name of the custom components package .gitignore file.
PACKAGE_GITIGNORE = ".gitignore"
# The name of the distribution directory as result of a build.
@@ -29,6 +30,6 @@ class CustomComponents(SimpleNamespace):
"testpypi": "https://test.pypi.org/legacy/",
}
# The .gitignore file for the custom component project.
- FILE = ".gitignore"
+ FILE = Path(".gitignore")
# Files to gitignore.
DEFAULTS = {"__pycache__/", "*.py[cod]", "*.egg-info/", "dist/"}
diff --git a/reflex/constants/event.py b/reflex/constants/event.py
index aa6f8c713..d454e6ea8 100644
--- a/reflex/constants/event.py
+++ b/reflex/constants/event.py
@@ -1,4 +1,5 @@
"""Event-related constants."""
+
from enum import Enum
from types import SimpleNamespace
@@ -9,6 +10,8 @@ class Endpoint(Enum):
PING = "ping"
EVENT = "_event"
UPLOAD = "_upload"
+ AUTH_CODESPACE = "auth-codespace"
+ HEALTH = "_health"
def __str__(self) -> str:
"""Get the string representation of the endpoint.
@@ -93,3 +96,5 @@ class EventTriggers(SimpleNamespace):
ON_CLEAR_SERVER_ERRORS = "on_clear_server_errors"
ON_VALUE_COMMIT = "on_value_commit"
ON_SELECT = "on_select"
+ ON_ANIMATION_START = "on_animation_start"
+ ON_ANIMATION_END = "on_animation_end"
diff --git a/reflex/constants/installer.py b/reflex/constants/installer.py
index 5bf9b365e..f720218e3 100644
--- a/reflex/constants/installer.py
+++ b/reflex/constants/installer.py
@@ -1,11 +1,13 @@
"""File for constants related to the installation process. (Bun/FNM/Node)."""
+
from __future__ import annotations
-import os
import platform
+from pathlib import Path
from types import SimpleNamespace
-from .base import IS_WINDOWS, Dirs, Reflex
+from .base import IS_WINDOWS
+from .utils import classproperty
def get_fnm_name() -> str | None:
@@ -35,22 +37,44 @@ class Bun(SimpleNamespace):
"""Bun constants."""
# The Bun version.
- VERSION = "1.1.6"
+ VERSION = "1.1.29"
+
# Min Bun Version
MIN_VERSION = "0.7.0"
- # The directory to store the bun.
- ROOT_PATH = os.path.join(Reflex.DIR, "bun")
- # Default bun path.
- DEFAULT_PATH = os.path.join(
- ROOT_PATH, "bin", "bun" if not IS_WINDOWS else "bun.exe"
- )
+
# URL to bun install script.
- INSTALL_URL = "https://bun.sh/install"
+ INSTALL_URL = "https://raw.githubusercontent.com/reflex-dev/reflex/main/scripts/bun_install.sh"
+
# URL to windows install script.
WINDOWS_INSTALL_URL = (
"https://raw.githubusercontent.com/reflex-dev/reflex/main/scripts/install.ps1"
)
+ # Path of the bunfig file
+ CONFIG_PATH = "bunfig.toml"
+
+ @classproperty
+ @classmethod
+ def ROOT_PATH(cls):
+ """The directory to store the bun.
+
+ Returns:
+ The directory to store the bun.
+ """
+ from reflex.config import environment
+
+ return environment.REFLEX_DIR / "bun"
+
+ @classproperty
+ @classmethod
+ def DEFAULT_PATH(cls):
+ """Default bun path.
+
+ Returns:
+ The default bun path.
+ """
+ return cls.ROOT_PATH / "bin" / ("bun" if not IS_WINDOWS else "bun.exe")
+
# FNM config.
class Fnm(SimpleNamespace):
@@ -58,40 +82,81 @@ class Fnm(SimpleNamespace):
# The FNM version.
VERSION = "1.35.1"
- # The directory to store fnm.
- DIR = os.path.join(Reflex.DIR, "fnm")
+
FILENAME = get_fnm_name()
- # The fnm executable binary.
- EXE = os.path.join(DIR, "fnm.exe" if IS_WINDOWS else "fnm")
# The URL to the fnm release binary
INSTALL_URL = (
f"https://github.com/Schniz/fnm/releases/download/v{VERSION}/{FILENAME}.zip"
)
+ @classproperty
+ @classmethod
+ def DIR(cls) -> Path:
+ """The directory to store fnm.
+
+ Returns:
+ The directory to store fnm.
+ """
+ from reflex.config import environment
+
+ return environment.REFLEX_DIR / "fnm"
+
+ @classproperty
+ @classmethod
+ def EXE(cls):
+ """The fnm executable binary.
+
+ Returns:
+ The fnm executable binary.
+ """
+ return cls.DIR / ("fnm.exe" if IS_WINDOWS else "fnm")
+
# Node / NPM config
class Node(SimpleNamespace):
"""Node/ NPM constants."""
# The Node version.
- VERSION = "18.17.0"
+ VERSION = "22.11.0"
# The minimum required node version.
- MIN_VERSION = "18.17.0"
+ MIN_VERSION = "18.18.0"
- # The node bin path.
- BIN_PATH = os.path.join(
- Fnm.DIR,
- "node-versions",
- f"v{VERSION}",
- "installation",
- "bin" if not IS_WINDOWS else "",
- )
- # The default path where node is installed.
- PATH = os.path.join(BIN_PATH, "node.exe" if IS_WINDOWS else "node")
+ @classproperty
+ @classmethod
+ def BIN_PATH(cls):
+ """The node bin path.
- # The default path where npm is installed.
- NPM_PATH = os.path.join(BIN_PATH, "npm")
+ Returns:
+ The node bin path.
+ """
+ return (
+ Fnm.DIR
+ / "node-versions"
+ / f"v{cls.VERSION}"
+ / "installation"
+ / ("bin" if not IS_WINDOWS else "")
+ )
+
+ @classproperty
+ @classmethod
+ def PATH(cls):
+ """The default path where node is installed.
+
+ Returns:
+ The default path where node is installed.
+ """
+ return cls.BIN_PATH / ("node.exe" if IS_WINDOWS else "node")
+
+ @classproperty
+ @classmethod
+ def NPM_PATH(cls):
+ """The default path where npm is installed.
+
+ Returns:
+ The default path where npm is installed.
+ """
+ return cls.BIN_PATH / "npm"
class PackageJson(SimpleNamespace):
@@ -105,22 +170,24 @@ class PackageJson(SimpleNamespace):
EXPORT_SITEMAP = "next build && next-sitemap"
PROD = "next start"
- PATH = os.path.join(Dirs.WEB, "package.json")
+ PATH = "package.json"
DEPENDENCIES = {
- "@emotion/react": "11.11.1",
- "axios": "1.6.0",
+ "@babel/standalone": "7.26.0",
+ "@emotion/react": "11.13.3",
+ "axios": "1.7.7",
"json5": "2.2.3",
- "next": "14.0.1",
- "next-sitemap": "4.1.8",
- "next-themes": "0.2.1",
- "react": "18.2.0",
- "react-dom": "18.2.0",
- "react-focus-lock": "2.11.3",
- "socket.io-client": "4.6.1",
- "universal-cookie": "4.0.4",
+ "next": "15.0.1",
+ "next-sitemap": "4.2.3",
+ "next-themes": "0.3.0",
+ "react": "18.3.1",
+ "react-dom": "18.3.1",
+ "react-focus-lock": "2.13.2",
+ "socket.io-client": "4.8.1",
+ "universal-cookie": "7.2.1",
}
DEV_DEPENDENCIES = {
- "autoprefixer": "10.4.14",
- "postcss": "8.4.31",
+ "autoprefixer": "10.4.20",
+ "postcss": "8.4.47",
+ "postcss-import": "16.1.0",
}
diff --git a/reflex/constants/state.py b/reflex/constants/state.py
new file mode 100644
index 000000000..aa0e2f97f
--- /dev/null
+++ b/reflex/constants/state.py
@@ -0,0 +1,11 @@
+"""State-related constants."""
+
+from enum import Enum
+
+
+class StateManagerMode(str, Enum):
+ """State manager constants."""
+
+ DISK = "disk"
+ MEMORY = "memory"
+ REDIS = "redis"
diff --git a/reflex/constants/style.py b/reflex/constants/style.py
index d0f72995e..403acd4ba 100644
--- a/reflex/constants/style.py
+++ b/reflex/constants/style.py
@@ -1,22 +1,16 @@
"""Style constants."""
-import os
from types import SimpleNamespace
-from reflex.constants.base import Dirs
-
-# The directory where styles are located.
-STYLES_DIR = os.path.join(Dirs.WEB, "styles")
-
class Tailwind(SimpleNamespace):
"""Tailwind constants."""
# The Tailwindcss version
- VERSION = "tailwindcss@3.3.2"
+ VERSION = "tailwindcss@3.4.14"
# The Tailwind config.
- CONFIG = os.path.join(Dirs.WEB, "tailwind.config.js")
+ CONFIG = "tailwind.config.js"
# Default Tailwind content paths
CONTENT = ["./pages/**/*.{js,ts,jsx,tsx}", "./utils/**/*.{js,ts,jsx,tsx}"]
- # Relative tailwind style path to root stylesheet in STYLES_DIR.
+ # Relative tailwind style path to root stylesheet in Dirs.STYLES.
ROOT_STYLE_PATH = "./tailwind.css"
diff --git a/reflex/constants/utils.py b/reflex/constants/utils.py
new file mode 100644
index 000000000..48797afbf
--- /dev/null
+++ b/reflex/constants/utils.py
@@ -0,0 +1,32 @@
+"""Utility functions for constants."""
+
+from typing import Any, Callable, Generic, Type
+
+from typing_extensions import TypeVar
+
+T = TypeVar("T")
+V = TypeVar("V")
+
+
+class classproperty(Generic[T, V]):
+ """A class property decorator."""
+
+ def __init__(self, getter: Callable[[Type[T]], V]) -> None:
+ """Initialize the class property.
+
+ Args:
+ getter: The getter function.
+ """
+ self.getter = getattr(getter, "__func__", getter)
+
+ def __get__(self, instance: Any, owner: Type[T]) -> V:
+ """Get the value of the class property.
+
+ Args:
+ instance: The instance of the class.
+ owner: The class itself.
+
+ Returns:
+ The value of the class property.
+ """
+ return self.getter(owner)
diff --git a/reflex/custom_components/custom_components.py b/reflex/custom_components/custom_components.py
index ec35fb5c4..ddda3de56 100644
--- a/reflex/custom_components/custom_components.py
+++ b/reflex/custom_components/custom_components.py
@@ -17,7 +17,7 @@ import typer
from tomlkit.exceptions import TOMLKitError
from reflex import constants
-from reflex.config import get_config
+from reflex.config import environment, get_config
from reflex.constants import CustomComponents
from reflex.utils import console
@@ -36,7 +36,7 @@ POST_CUSTOM_COMPONENTS_GALLERY_TIMEOUT = 15
@contextmanager
-def set_directory(working_directory: str):
+def set_directory(working_directory: str | Path):
"""Context manager that sets the working directory.
Args:
@@ -45,7 +45,8 @@ def set_directory(working_directory: str):
Yields:
Yield to the caller to perform operations in the working directory.
"""
- current_directory = os.getcwd()
+ current_directory = Path.cwd()
+ working_directory = Path(working_directory)
try:
os.chdir(working_directory)
yield
@@ -62,12 +63,14 @@ def _create_package_config(module_name: str, package_name: str):
"""
from reflex.compiler import templates
- with open(CustomComponents.PYPROJECT_TOML, "w") as f:
- f.write(
- templates.CUSTOM_COMPONENTS_PYPROJECT_TOML.render(
- module_name=module_name, package_name=package_name
- )
+ pyproject = Path(CustomComponents.PYPROJECT_TOML)
+ pyproject.write_text(
+ templates.CUSTOM_COMPONENTS_PYPROJECT_TOML.render(
+ module_name=module_name,
+ package_name=package_name,
+ reflex_version=constants.Reflex.VERSION,
)
+ )
def _get_package_config(exit_on_fail: bool = True) -> dict:
@@ -82,11 +85,11 @@ def _get_package_config(exit_on_fail: bool = True) -> dict:
Raises:
Exit: If the pyproject.toml file is not found.
"""
+ pyproject = Path(CustomComponents.PYPROJECT_TOML)
try:
- with open(CustomComponents.PYPROJECT_TOML, "rb") as f:
- return dict(tomlkit.load(f))
+ return dict(tomlkit.loads(pyproject.read_bytes()))
except (OSError, TOMLKitError) as ex:
- console.error(f"Unable to read from pyproject.toml due to {ex}")
+ console.error(f"Unable to read from {pyproject} due to {ex}")
if exit_on_fail:
raise typer.Exit(code=1) from ex
raise
@@ -101,17 +104,17 @@ def _create_readme(module_name: str, package_name: str):
"""
from reflex.compiler import templates
- with open(CustomComponents.PACKAGE_README, "w") as f:
- f.write(
- templates.CUSTOM_COMPONENTS_README.render(
- module_name=module_name,
- package_name=package_name,
- )
+ readme = Path(CustomComponents.PACKAGE_README)
+ readme.write_text(
+ templates.CUSTOM_COMPONENTS_README.render(
+ module_name=module_name,
+ package_name=package_name,
)
+ )
def _write_source_and_init_py(
- custom_component_src_dir: str,
+ custom_component_src_dir: Path,
component_class_name: str,
module_name: str,
):
@@ -124,27 +127,17 @@ def _write_source_and_init_py(
"""
from reflex.compiler import templates
- with open(
- os.path.join(
- custom_component_src_dir,
- f"{module_name}.py",
- ),
- "w",
- ) as f:
- f.write(
- templates.CUSTOM_COMPONENTS_SOURCE.render(
- component_class_name=component_class_name, module_name=module_name
- )
+ module_path = custom_component_src_dir / f"{module_name}.py"
+ module_path.write_text(
+ templates.CUSTOM_COMPONENTS_SOURCE.render(
+ component_class_name=component_class_name, module_name=module_name
)
+ )
- with open(
- os.path.join(
- custom_component_src_dir,
- CustomComponents.INIT_FILE,
- ),
- "w",
- ) as f:
- f.write(templates.CUSTOM_COMPONENTS_INIT_FILE.render(module_name=module_name))
+ init_path = custom_component_src_dir / CustomComponents.INIT_FILE
+ init_path.write_text(
+ templates.CUSTOM_COMPONENTS_INIT_FILE.render(module_name=module_name)
+ )
def _populate_demo_app(name_variants: NameVariants):
@@ -190,7 +183,7 @@ def _get_default_library_name_parts() -> list[str]:
Returns:
The parts of default library name.
"""
- current_dir_name = os.getcwd().split(os.path.sep)[-1]
+ current_dir_name = Path.cwd().name
cleaned_dir_name = re.sub("[^0-9a-zA-Z-_]+", "", current_dir_name).lower()
parts = [part for part in re.split("-|_", cleaned_dir_name) if part]
@@ -267,7 +260,7 @@ def _validate_library_name(library_name: str | None) -> NameVariants:
# Module name is the snake case.
module_name = "_".join(name_parts)
- custom_component_module_dir = f"reflex_{module_name}"
+ custom_component_module_dir = Path(f"reflex_{module_name}")
console.debug(f"Custom component source directory: {custom_component_module_dir}")
# Use the same name for the directory and the app.
@@ -343,7 +336,7 @@ def init(
console.set_log_level(loglevel)
- if os.path.exists(CustomComponents.PYPROJECT_TOML):
+ if CustomComponents.PYPROJECT_TOML.exists():
console.error(f"A {CustomComponents.PYPROJECT_TOML} already exists. Aborting.")
typer.Exit(code=1)
@@ -616,15 +609,17 @@ def publish(
help="The API token to use for authentication on python package repository. If token is provided, no username/password should be provided at the same time",
),
username: Optional[str] = typer.Option(
- None,
+ environment.TWINE_USERNAME,
"-u",
"--username",
+ show_default="TWINE_USERNAME environment variable value if set",
help="The username to use for authentication on python package repository. Username and password must both be provided.",
),
password: Optional[str] = typer.Option(
- None,
+ environment.TWINE_PASSWORD,
"-p",
"--password",
+ show_default="TWINE_PASSWORD environment variable value if set",
help="The password to use for authentication on python package repository. Username and password must both be provided.",
),
build: bool = typer.Option(
@@ -667,6 +662,9 @@ def publish(
# Validate the credentials.
username, password = _validate_credentials(username, password, token)
+ # Minimal Validation of the pyproject.toml.
+ _min_validate_project_info()
+
# Get the version to publish from the pyproject.toml.
version_to_publish = _get_version_to_publish()
@@ -735,6 +733,34 @@ def _process_entered_list(input: str | None) -> list | None:
return [t.strip() for t in (input or "").split(",") if t if input] or None
+def _min_validate_project_info():
+ """Ensures minimal project information in the pyproject.toml file.
+
+ Raises:
+ Exit: If the pyproject.toml file is ill-formed.
+ """
+ pyproject_toml = _get_package_config()
+
+ project = pyproject_toml.get("project")
+ if project is None:
+ console.error(
+ f"The project section is not found in {CustomComponents.PYPROJECT_TOML}"
+ )
+ raise typer.Exit(code=1)
+
+ if not project.get("name"):
+ console.error(
+ f"The project name is not found in {CustomComponents.PYPROJECT_TOML}"
+ )
+ raise typer.Exit(code=1)
+
+ if not project.get("version"):
+ console.error(
+ f"The project version is not found in {CustomComponents.PYPROJECT_TOML}"
+ )
+ raise typer.Exit(code=1)
+
+
def _validate_project_info():
"""Validate the project information in the pyproject.toml file.
@@ -742,18 +768,10 @@ def _validate_project_info():
Exit: If the pyproject.toml file is ill-formed.
"""
pyproject_toml = _get_package_config()
-
- try:
- project = pyproject_toml.get("project", {})
- if not project:
- console.error("The project section not found in pyproject.toml")
- raise typer.Exit(code=1)
- console.print(
- f'Double check the information before publishing: {project["name"]} version {project["version"]}'
- )
- except KeyError as ke:
- console.error(f"The pyproject.toml is possibly ill-formed due to {ke}")
- raise typer.Exit(code=1) from ke
+ project = pyproject_toml["project"]
+ console.print(
+ f'Double check the information before publishing: {project["name"]} version {project["version"]}'
+ )
console.print("Update or enter to keep the current information.")
project["description"] = console.ask(
diff --git a/reflex/event.py b/reflex/event.py
index e1ae88076..c2e6955f6 100644
--- a/reflex/event.py
+++ b/reflex/event.py
@@ -2,25 +2,51 @@
from __future__ import annotations
+import dataclasses
import inspect
+import sys
+import types
+import urllib.parse
from base64 import b64encode
-from types import FunctionType
+from functools import partial
from typing import (
Any,
Callable,
Dict,
+ Generic,
List,
Optional,
+ Sequence,
Tuple,
+ Type,
+ TypeVar,
Union,
get_type_hints,
+ overload,
)
+from typing_extensions import ParamSpec, Protocol, get_args, get_origin
+
from reflex import constants
-from reflex.base import Base
-from reflex.utils import format
-from reflex.utils.types import ArgsSpec
-from reflex.vars import BaseVar, Var
+from reflex.utils import console, format
+from reflex.utils.exceptions import (
+ EventFnArgMismatch,
+ EventHandlerArgMismatch,
+ EventHandlerArgTypeMismatch,
+)
+from reflex.utils.types import ArgsSpec, GenericType, typehint_issubclass
+from reflex.vars import VarData
+from reflex.vars.base import (
+ LiteralVar,
+ Var,
+)
+from reflex.vars.function import (
+ ArgsFunctionOperation,
+ FunctionStringVar,
+ FunctionVar,
+ VarOperationCall,
+)
+from reflex.vars.object import ObjectVar
try:
from typing import Annotated
@@ -28,7 +54,11 @@ except ImportError:
from typing_extensions import Annotated
-class Event(Base):
+@dataclasses.dataclass(
+ init=True,
+ frozen=True,
+)
+class Event:
"""An event that describes any state change in the app."""
# The token to specify the client that the event is for.
@@ -38,10 +68,10 @@ class Event(Base):
name: str
# The routing data where event occurred
- router_data: Dict[str, Any] = {}
+ router_data: Dict[str, Any] = dataclasses.field(default_factory=dict)
# The event payload.
- payload: Dict[str, Any] = {}
+ payload: Dict[str, Any] = dataclasses.field(default_factory=dict)
@property
def substate_token(self) -> str:
@@ -57,7 +87,7 @@ class Event(Base):
BACKGROUND_TASK_MARKER = "_reflex_background_task"
-def background(fn):
+def background(fn, *, __internal_reflex_call: bool = False):
"""Decorator to mark event handler as running in the background.
Args:
@@ -70,17 +100,28 @@ def background(fn):
Raises:
TypeError: If the function is not a coroutine function or async generator.
"""
+ if not __internal_reflex_call:
+ console.deprecate(
+ "background-decorator",
+ "Use `rx.event(background=True)` instead.",
+ "0.6.5",
+ "0.7.0",
+ )
if not inspect.iscoroutinefunction(fn) and not inspect.isasyncgenfunction(fn):
raise TypeError("Background task must be async function or generator.")
setattr(fn, BACKGROUND_TASK_MARKER, True)
return fn
-class EventActionsMixin(Base):
+@dataclasses.dataclass(
+ init=True,
+ frozen=True,
+)
+class EventActionsMixin:
"""Mixin for DOM event actions."""
# Whether to `preventDefault` or `stopPropagation` on the event.
- event_actions: Dict[str, Union[bool, int]] = {}
+ event_actions: Dict[str, Union[bool, int]] = dataclasses.field(default_factory=dict)
@property
def stop_propagation(self):
@@ -89,8 +130,9 @@ class EventActionsMixin(Base):
Returns:
New EventHandler-like with stopPropagation set to True.
"""
- return self.copy(
- update={"event_actions": {"stopPropagation": True, **self.event_actions}},
+ return dataclasses.replace(
+ self,
+ event_actions={"stopPropagation": True, **self.event_actions},
)
@property
@@ -100,8 +142,9 @@ class EventActionsMixin(Base):
Returns:
New EventHandler-like with preventDefault set to True.
"""
- return self.copy(
- update={"event_actions": {"preventDefault": True, **self.event_actions}},
+ return dataclasses.replace(
+ self,
+ event_actions={"preventDefault": True, **self.event_actions},
)
def throttle(self, limit_ms: int):
@@ -113,8 +156,9 @@ class EventActionsMixin(Base):
Returns:
New EventHandler-like with throttle set to limit_ms.
"""
- return self.copy(
- update={"event_actions": {"throttle": limit_ms, **self.event_actions}},
+ return dataclasses.replace(
+ self,
+ event_actions={"throttle": limit_ms, **self.event_actions},
)
def debounce(self, delay_ms: int):
@@ -126,26 +170,25 @@ class EventActionsMixin(Base):
Returns:
New EventHandler-like with debounce set to delay_ms.
"""
- return self.copy(
- update={"event_actions": {"debounce": delay_ms, **self.event_actions}},
+ return dataclasses.replace(
+ self,
+ event_actions={"debounce": delay_ms, **self.event_actions},
)
+@dataclasses.dataclass(
+ init=True,
+ frozen=True,
+)
class EventHandler(EventActionsMixin):
"""An event handler responds to an event to update the state."""
# The function to call in response to the event.
- fn: Any
+ fn: Any = dataclasses.field(default=None)
# The full name of the state class this event handler is attached to.
# Empty string means this event handler is a server side event.
- state_full_name: str = ""
-
- class Config:
- """The Pydantic config."""
-
- # Needed to allow serialization of Callable.
- frozen = True
+ state_full_name: str = dataclasses.field(default="")
@classmethod
def __class_getitem__(cls, args_spec: str) -> Annotated:
@@ -186,7 +229,7 @@ class EventHandler(EventActionsMixin):
# Get the function args.
fn_args = inspect.getfullargspec(self.fn).args[1:]
- fn_args = (Var.create_safe(arg) for arg in fn_args)
+ fn_args = (Var(_js_expr=arg) for arg in fn_args)
# Construct the payload.
values = []
@@ -197,7 +240,7 @@ class EventHandler(EventActionsMixin):
# Otherwise, convert to JSON.
try:
- values.append(Var.create(arg, _var_is_string=isinstance(arg, str)))
+ values.append(LiteralVar.create(arg))
except TypeError as e:
raise EventHandlerTypeError(
f"Arguments to event handlers must be Vars or JSON-serializable. Got {arg} of type {type(arg)}."
@@ -210,6 +253,10 @@ class EventHandler(EventActionsMixin):
)
+@dataclasses.dataclass(
+ init=True,
+ frozen=True,
+)
class EventSpec(EventActionsMixin):
"""An event specification.
@@ -218,19 +265,35 @@ class EventSpec(EventActionsMixin):
"""
# The event handler.
- handler: EventHandler
+ handler: EventHandler = dataclasses.field(default=None) # type: ignore
# The handler on the client to process event.
- client_handler_name: str = ""
+ client_handler_name: str = dataclasses.field(default="")
# The arguments to pass to the function.
- args: Tuple[Tuple[Var, Var], ...] = ()
+ args: Tuple[Tuple[Var, Var], ...] = dataclasses.field(default_factory=tuple)
- class Config:
- """The Pydantic config."""
+ def __init__(
+ self,
+ handler: EventHandler,
+ event_actions: Dict[str, Union[bool, int]] | None = None,
+ client_handler_name: str = "",
+ args: Tuple[Tuple[Var, Var], ...] = tuple(),
+ ):
+ """Initialize an EventSpec.
- # Required to allow tuple fields.
- frozen = True
+ Args:
+ event_actions: The event actions.
+ handler: The event handler.
+ client_handler_name: The client handler name.
+ args: The arguments to pass to the function.
+ """
+ if event_actions is None:
+ event_actions = {}
+ object.__setattr__(self, "event_actions", event_actions)
+ object.__setattr__(self, "handler", handler)
+ object.__setattr__(self, "client_handler_name", client_handler_name)
+ object.__setattr__(self, "args", args or tuple())
def with_args(self, args: Tuple[Tuple[Var, Var], ...]) -> EventSpec:
"""Copy the event spec, with updated args.
@@ -264,13 +327,13 @@ class EventSpec(EventActionsMixin):
# Get the remaining unfilled function args.
fn_args = inspect.getfullargspec(self.handler.fn).args[1 + len(self.args) :]
- fn_args = (Var.create_safe(arg) for arg in fn_args)
+ fn_args = (Var(_js_expr=arg) for arg in fn_args)
# Construct the payload.
values = []
for arg in args:
try:
- values.append(Var.create(arg, _var_is_string=isinstance(arg, str)))
+ values.append(LiteralVar.create(arg))
except TypeError as e:
raise EventHandlerTypeError(
f"Arguments to event handlers must be Vars or JSON-serializable. Got {arg} of type {type(arg)}."
@@ -279,6 +342,9 @@ class EventSpec(EventActionsMixin):
return self.with_args(self.args + new_payload)
+@dataclasses.dataclass(
+ frozen=True,
+)
class CallableEventSpec(EventSpec):
"""Decorate an EventSpec-returning function to act as both a EventSpec and a function.
@@ -298,10 +364,13 @@ class CallableEventSpec(EventSpec):
if fn is not None:
default_event_spec = fn()
super().__init__(
- fn=fn, # type: ignore
- **default_event_spec.dict(),
+ event_actions=default_event_spec.event_actions,
+ client_handler_name=default_event_spec.client_handler_name,
+ args=default_event_spec.args,
+ handler=default_event_spec.handler,
**kwargs,
)
+ object.__setattr__(self, "fn", fn)
else:
super().__init__(**kwargs)
@@ -325,42 +394,200 @@ class CallableEventSpec(EventSpec):
return self.fn(*args, **kwargs)
+@dataclasses.dataclass(
+ init=True,
+ frozen=True,
+)
class EventChain(EventActionsMixin):
"""Container for a chain of events that will be executed in order."""
- events: List[EventSpec]
+ events: Sequence[Union[EventSpec, EventVar, EventCallback]] = dataclasses.field(
+ default_factory=list
+ )
- args_spec: Optional[Callable]
+ args_spec: Optional[Union[Callable, Sequence[Callable]]] = dataclasses.field(
+ default=None
+ )
+
+ invocation: Optional[Var] = dataclasses.field(default=None)
+
+
+@dataclasses.dataclass(
+ init=True,
+ frozen=True,
+)
+class JavascriptHTMLInputElement:
+ """Interface for a Javascript HTMLInputElement https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement."""
+
+ value: str = ""
+
+
+@dataclasses.dataclass(
+ init=True,
+ frozen=True,
+)
+class JavascriptInputEvent:
+ """Interface for a Javascript InputEvent https://developer.mozilla.org/en-US/docs/Web/API/InputEvent."""
+
+ target: JavascriptHTMLInputElement = JavascriptHTMLInputElement()
+
+
+@dataclasses.dataclass(
+ init=True,
+ frozen=True,
+)
+class JavasciptKeyboardEvent:
+ """Interface for a Javascript KeyboardEvent https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent."""
+
+ key: str = ""
+
+
+def input_event(e: Var[JavascriptInputEvent]) -> Tuple[Var[str]]:
+ """Get the value from an input event.
+
+ Args:
+ e: The input event.
+
+ Returns:
+ The value from the input event.
+ """
+ return (e.target.value,)
+
+
+def key_event(e: Var[JavasciptKeyboardEvent]) -> Tuple[Var[str]]:
+ """Get the key from a keyboard event.
+
+ Args:
+ e: The keyboard event.
+
+ Returns:
+ The key from the keyboard event.
+ """
+ return (e.key,)
+
+
+def empty_event() -> Tuple[()]:
+ """Empty event handler.
+
+ Returns:
+ An empty tuple.
+ """
+ return tuple() # type: ignore
# These chains can be used for their side effects when no other events are desired.
-stop_propagation = EventChain(events=[], args_spec=lambda: []).stop_propagation
-prevent_default = EventChain(events=[], args_spec=lambda: []).prevent_default
+stop_propagation = EventChain(events=[], args_spec=empty_event).stop_propagation
+prevent_default = EventChain(events=[], args_spec=empty_event).prevent_default
-class Target(Base):
- """A Javascript event target."""
-
- checked: bool = False
- value: Any = None
+T = TypeVar("T")
+U = TypeVar("U")
-class FrontendEvent(Base):
- """A Javascript event."""
+# def identity_event(event_type: Type[T]) -> Callable[[Var[T]], Tuple[Var[T]]]:
+# """A helper function that returns the input event as output.
- target: Target = Target()
- key: str = ""
- value: Any = None
+# Args:
+# event_type: The type of the event.
+
+# Returns:
+# A function that returns the input event as output.
+# """
+
+# def inner(ev: Var[T]) -> Tuple[Var[T]]:
+# return (ev,)
+
+# inner.__signature__ = inspect.signature(inner).replace( # type: ignore
+# parameters=[
+# inspect.Parameter(
+# "ev",
+# kind=inspect.Parameter.POSITIONAL_OR_KEYWORD,
+# annotation=Var[event_type],
+# )
+# ],
+# return_annotation=Tuple[Var[event_type]],
+# )
+# inner.__annotations__["ev"] = Var[event_type]
+# inner.__annotations__["return"] = Tuple[Var[event_type]]
+
+# return inner
-class FileUpload(Base):
+class IdentityEventReturn(Generic[T], Protocol):
+ """Protocol for an identity event return."""
+
+ def __call__(self, *values: Var[T]) -> Tuple[Var[T], ...]:
+ """Return the input values.
+
+ Args:
+ *values: The values to return.
+
+ Returns:
+ The input values.
+ """
+ return values
+
+
+@overload
+def identity_event(event_type: Type[T], /) -> Callable[[Var[T]], Tuple[Var[T]]]: ... # type: ignore
+
+
+@overload
+def identity_event(
+ event_type_1: Type[T], event_type2: Type[U], /
+) -> Callable[[Var[T], Var[U]], Tuple[Var[T], Var[U]]]: ...
+
+
+@overload
+def identity_event(*event_types: Type[T]) -> IdentityEventReturn[T]: ...
+
+
+def identity_event(*event_types: Type[T]) -> IdentityEventReturn[T]: # type: ignore
+ """A helper function that returns the input event as output.
+
+ Args:
+ *event_types: The types of the events.
+
+ Returns:
+ A function that returns the input event as output.
+ """
+
+ def inner(*values: Var[T]) -> Tuple[Var[T], ...]:
+ return values
+
+ inner_type = tuple(Var[event_type] for event_type in event_types)
+ return_annotation = Tuple[inner_type] # type: ignore
+
+ inner.__signature__ = inspect.signature(inner).replace( # type: ignore
+ parameters=[
+ inspect.Parameter(
+ f"ev_{i}",
+ kind=inspect.Parameter.POSITIONAL_OR_KEYWORD,
+ annotation=Var[event_type],
+ )
+ for i, event_type in enumerate(event_types)
+ ],
+ return_annotation=return_annotation,
+ )
+ for i, event_type in enumerate(event_types):
+ inner.__annotations__[f"ev_{i}"] = Var[event_type]
+ inner.__annotations__["return"] = return_annotation
+
+ return inner
+
+
+@dataclasses.dataclass(
+ init=True,
+ frozen=True,
+)
+class FileUpload:
"""Class to represent a file upload."""
upload_id: Optional[str] = None
on_upload_progress: Optional[Union[EventHandler, Callable]] = None
@staticmethod
- def on_upload_progress_args_spec(_prog: Dict[str, Union[int, float, bool]]):
+ def on_upload_progress_args_spec(_prog: Var[Dict[str, Union[int, float, bool]]]):
"""Args spec for on_upload_progress event handler.
Returns:
@@ -386,17 +613,18 @@ class FileUpload(Base):
)
upload_id = self.upload_id or DEFAULT_UPLOAD_ID
-
spec_args = [
(
- Var.create_safe("files"),
- Var.create_safe(f"filesById.{upload_id}")._replace(
- _var_data=upload_files_context_var_data
- ),
+ Var(_js_expr="files"),
+ Var(
+ _js_expr="filesById",
+ _var_type=Dict[str, Any],
+ _var_data=VarData.merge(upload_files_context_var_data),
+ ).to(ObjectVar)[LiteralVar.create(upload_id)],
),
(
- Var.create_safe("upload_id"),
- Var.create_safe(upload_id, _var_is_string=True),
+ Var(_js_expr="upload_id"),
+ LiteralVar.create(upload_id),
),
]
if self.on_upload_progress is not None:
@@ -415,18 +643,19 @@ class FileUpload(Base):
) # type: ignore
else:
raise ValueError(f"{on_upload_progress} is not a valid event handler.")
+ if isinstance(events, Var):
+ raise ValueError(f"{on_upload_progress} cannot return a var {events}.")
on_upload_progress_chain = EventChain(
- events=events,
+ events=[*events],
args_spec=self.on_upload_progress_args_spec,
)
formatted_chain = str(format.format_prop(on_upload_progress_chain))
spec_args.append(
(
- Var.create_safe("on_upload_progress"),
- BaseVar(
- _var_name=formatted_chain.strip("{}"),
- _var_type=EventChain,
- ),
+ Var(_js_expr="on_upload_progress"),
+ FunctionStringVar(
+ formatted_chain.strip("{}"),
+ ).to(FunctionVar, EventChain),
),
)
return EventSpec(
@@ -462,24 +691,36 @@ def server_side(name: str, sig: inspect.Signature, **kwargs) -> EventSpec:
return EventSpec(
handler=EventHandler(fn=fn),
args=tuple(
- (Var.create_safe(k), Var.create_safe(v, _var_is_string=isinstance(v, str)))
+ (
+ Var(_js_expr=k),
+ LiteralVar.create(v),
+ )
for k, v in kwargs.items()
),
)
-def redirect(path: str | Var[str], external: Optional[bool] = False) -> EventSpec:
+def redirect(
+ path: str | Var[str],
+ external: Optional[bool] = False,
+ replace: Optional[bool] = False,
+) -> EventSpec:
"""Redirect to a new path.
Args:
path: The path to redirect to.
external: Whether to open in new tab or not.
+ replace: If True, the current page will not create a new history entry.
Returns:
An event to redirect to the path.
"""
return server_side(
- "_redirect", get_fn_signature(redirect), path=path, external=external
+ "_redirect",
+ get_fn_signature(redirect),
+ path=path,
+ external=external,
+ replace=replace,
)
@@ -495,6 +736,15 @@ def console_log(message: str | Var[str]) -> EventSpec:
return server_side("_console", get_fn_signature(console_log), message=message)
+def back() -> EventSpec:
+ """Do a history.back on the browser.
+
+ Returns:
+ An event to go back one page.
+ """
+ return call_script("window.history.back()")
+
+
def window_alert(message: str | Var[str]) -> EventSpec:
"""Create a window alert on the browser.
@@ -519,22 +769,29 @@ def set_focus(ref: str) -> EventSpec:
return server_side(
"_set_focus",
get_fn_signature(set_focus),
- ref=Var.create_safe(format.format_ref(ref), _var_is_string=True),
+ ref=LiteralVar.create(format.format_ref(ref)),
)
-def scroll_to(elem_id: str) -> EventSpec:
+def scroll_to(elem_id: str, align_to_top: bool | Var[bool] = True) -> EventSpec:
"""Select the id of a html element for scrolling into view.
Args:
- elem_id: the id of the element
+ elem_id: The id of the element to scroll to.
+ align_to_top: Whether to scroll to the top (True) or bottom (False) of the element.
Returns:
An EventSpec to scroll the page to the selected element.
"""
- js_code = f"document.getElementById('{elem_id}').scrollIntoView();"
+ get_element_by_id = FunctionStringVar.create("document.getElementById")
- return call_script(js_code)
+ return call_script(
+ get_element_by_id(elem_id)
+ .call(elem_id)
+ .to(ObjectVar)
+ .scrollIntoView.to(FunctionVar)
+ .call(align_to_top)
+ )
def set_value(ref: str, value: Any) -> EventSpec:
@@ -550,7 +807,7 @@ def set_value(ref: str, value: Any) -> EventSpec:
return server_side(
"_set_value",
get_fn_signature(set_value),
- ref=Var.create_safe(format.format_ref(ref), _var_is_string=True),
+ ref=LiteralVar.create(format.format_ref(ref)),
value=value,
)
@@ -603,6 +860,34 @@ def remove_local_storage(key: str) -> EventSpec:
)
+def clear_session_storage() -> EventSpec:
+ """Set a value in the session storage on the frontend.
+
+ Returns:
+ EventSpec: An event to clear the session storage.
+ """
+ return server_side(
+ "_clear_session_storage",
+ get_fn_signature(clear_session_storage),
+ )
+
+
+def remove_session_storage(key: str) -> EventSpec:
+ """Set a value in the session storage on the frontend.
+
+ Args:
+ key: The key identifying the variable in the session storage to remove.
+
+ Returns:
+ EventSpec: An event to remove an item based on the provided key in session storage.
+ """
+ return server_side(
+ "_remove_session_storage",
+ get_fn_signature(remove_session_storage),
+ key=key,
+ )
+
+
def set_clipboard(content: str) -> EventSpec:
"""Set the text in content in the clipboard.
@@ -657,22 +942,18 @@ def download(
if isinstance(data, str):
# Caller provided a plain text string to download.
- url = "data:text/plain," + data
+ url = "data:text/plain," + urllib.parse.quote(data)
elif isinstance(data, Var):
# Need to check on the frontend if the Var already looks like a data: URI.
- is_data_url = data._replace(
- _var_name=(
- f"typeof {data._var_full_name} == 'string' && "
- f"{data._var_full_name}.startsWith('data:')"
- ),
- _var_type=bool,
- _var_is_string=False,
- _var_full_name_needs_state_prefix=False,
- )
+
+ is_data_url = (data.js_type() == "string") & (
+ data.to(str).startswith("data:")
+ ) # type: ignore
+
# If it's a data: URI, use it as is, otherwise convert the Var to JSON in a data: URI.
url = cond( # type: ignore
is_data_url,
- data,
+ data.to(str),
"data:text/plain," + data.to_string(), # type: ignore
)
elif isinstance(data, bytes):
@@ -705,8 +986,14 @@ def _callback_arg_spec(eval_result):
def call_script(
- javascript_code: str,
- callback: EventHandler | Callable | None = None,
+ javascript_code: str | Var[str],
+ callback: (
+ EventSpec
+ | EventHandler
+ | Callable
+ | List[EventSpec | EventHandler | Callable]
+ | None
+ ) = None,
) -> EventSpec:
"""Create an event handler that executes arbitrary javascript code.
@@ -716,22 +1003,27 @@ def call_script(
Returns:
EventSpec: An event that will execute the client side javascript.
-
- Raises:
- ValueError: If the callback is not a valid event handler.
"""
callback_kwargs = {}
if callback is not None:
- arg_name = parse_args_spec(_callback_arg_spec)[0]._var_name
- if isinstance(callback, EventHandler):
- event_spec = call_event_handler(callback, _callback_arg_spec)
- elif isinstance(callback, FunctionType):
- event_spec = call_event_fn(callback, _callback_arg_spec)[0]
- else:
- raise ValueError("Cannot use {callback!r} as a call_script callback.")
callback_kwargs = {
- "callback": f"({arg_name}) => queueEvents([{format.format_event(event_spec)}], {constants.CompileVars.SOCKET})"
+ "callback": str(
+ format.format_queue_events(
+ callback,
+ args_spec=lambda result: [result],
+ ),
+ ),
}
+ if isinstance(javascript_code, str):
+ # When there is VarData, include it and eval the JS code inline on the client.
+ javascript_code, original_code = (
+ LiteralVar.create(javascript_code),
+ javascript_code,
+ )
+ if not javascript_code._get_all_var_data():
+ # Without VarData, cast to string and eval the code in the event loop.
+ javascript_code = str(Var(_js_expr=original_code))
+
return server_side(
"_call_script",
get_fn_signature(call_script),
@@ -767,7 +1059,8 @@ def get_hydrate_event(state) -> str:
def call_event_handler(
event_handler: EventHandler | EventSpec,
- arg_spec: ArgsSpec,
+ arg_spec: ArgsSpec | Sequence[ArgsSpec],
+ key: Optional[str] = None,
) -> EventSpec:
"""Call an event handler to get the event spec.
@@ -778,12 +1071,16 @@ def call_event_handler(
Args:
event_handler: The event handler.
arg_spec: The lambda that define the argument(s) to pass to the event handler.
+ key: The key to pass to the event handler.
Raises:
- ValueError: if number of arguments expected by event_handler doesn't match the spec.
+ EventHandlerArgMismatch: if number of arguments expected by event_handler doesn't match the spec.
Returns:
The event spec from calling the event handler.
+
+ # noqa: DAR401 failure
+
"""
parsed_args = parse_args_spec(arg_spec) # type: ignore
@@ -791,18 +1088,152 @@ def call_event_handler(
# Handle partial application of EventSpec args
return event_handler.add_args(*parsed_args)
- args = inspect.getfullargspec(event_handler.fn).args
- if len(args) == len(["self", *parsed_args]):
- return event_handler(*parsed_args) # type: ignore
- else:
- source = inspect.getsource(arg_spec) # type: ignore
- raise ValueError(
- f"number of arguments in {event_handler.fn.__qualname__} "
- f"doesn't match the definition of the event trigger '{source.strip().strip(',')}'"
+ provided_callback_fullspec = inspect.getfullargspec(event_handler.fn)
+
+ provided_callback_n_args = (
+ len(provided_callback_fullspec.args) - 1
+ ) # subtract 1 for bound self arg
+
+ if provided_callback_n_args != len(parsed_args):
+ raise EventHandlerArgMismatch(
+ "The number of arguments accepted by "
+ f"{event_handler.fn.__qualname__} ({provided_callback_n_args}) "
+ "does not match the arguments passed by the event trigger: "
+ f"{[str(v) for v in parsed_args]}\n"
+ "See https://reflex.dev/docs/events/event-arguments/"
)
+ all_arg_spec = [arg_spec] if not isinstance(arg_spec, Sequence) else arg_spec
-def parse_args_spec(arg_spec: ArgsSpec):
+ event_spec_return_types = list(
+ filter(
+ lambda event_spec_return_type: event_spec_return_type is not None
+ and get_origin(event_spec_return_type) is tuple,
+ (get_type_hints(arg_spec).get("return", None) for arg_spec in all_arg_spec),
+ )
+ )
+
+ if event_spec_return_types:
+ failures = []
+
+ for event_spec_index, event_spec_return_type in enumerate(
+ event_spec_return_types
+ ):
+ args = get_args(event_spec_return_type)
+
+ args_types_without_vars = [
+ arg if get_origin(arg) is not Var else get_args(arg)[0] for arg in args
+ ]
+
+ try:
+ type_hints_of_provided_callback = get_type_hints(event_handler.fn)
+ except NameError:
+ type_hints_of_provided_callback = {}
+
+ failed_type_check = False
+
+ # check that args of event handler are matching the spec if type hints are provided
+ for i, arg in enumerate(provided_callback_fullspec.args[1:]):
+ if arg not in type_hints_of_provided_callback:
+ continue
+
+ try:
+ compare_result = typehint_issubclass(
+ args_types_without_vars[i], type_hints_of_provided_callback[arg]
+ )
+ except TypeError:
+ # TODO: In 0.7.0, remove this block and raise the exception
+ # raise TypeError(
+ # f"Could not compare types {args_types_without_vars[i]} and {type_hints_of_provided_callback[arg]} for argument {arg} of {event_handler.fn.__qualname__} provided for {key}."
+ # ) from e
+ console.warn(
+ f"Could not compare types {args_types_without_vars[i]} and {type_hints_of_provided_callback[arg]} for argument {arg} of {event_handler.fn.__qualname__} provided for {key}."
+ )
+ compare_result = False
+
+ if compare_result:
+ continue
+ else:
+ failure = EventHandlerArgTypeMismatch(
+ f"Event handler {key} expects {args_types_without_vars[i]} for argument {arg} but got {type_hints_of_provided_callback[arg]} as annotated in {event_handler.fn.__qualname__} instead."
+ )
+ failures.append(failure)
+ failed_type_check = True
+ break
+
+ if not failed_type_check:
+ if event_spec_index:
+ args = get_args(event_spec_return_types[0])
+
+ args_types_without_vars = [
+ arg if get_origin(arg) is not Var else get_args(arg)[0]
+ for arg in args
+ ]
+
+ expect_string = ", ".join(
+ repr(arg) for arg in args_types_without_vars
+ ).replace("[", "\\[")
+
+ given_string = ", ".join(
+ repr(type_hints_of_provided_callback.get(arg, Any))
+ for arg in provided_callback_fullspec.args[1:]
+ ).replace("[", "\\[")
+
+ console.warn(
+ f"Event handler {key} expects ({expect_string}) -> () but got ({given_string}) -> () as annotated in {event_handler.fn.__qualname__} instead. "
+ f"This may lead to unexpected behavior but is intentionally ignored for {key}."
+ )
+ return event_handler(*parsed_args)
+
+ if failures:
+ console.deprecate(
+ "Mismatched event handler argument types",
+ "\n".join([str(f) for f in failures]),
+ "0.6.5",
+ "0.7.0",
+ )
+
+ return event_handler(*parsed_args) # type: ignore
+
+
+def unwrap_var_annotation(annotation: GenericType):
+ """Unwrap a Var annotation or return it as is if it's not Var[X].
+
+ Args:
+ annotation: The annotation to unwrap.
+
+ Returns:
+ The unwrapped annotation.
+ """
+ if get_origin(annotation) is Var and (args := get_args(annotation)):
+ return args[0]
+ return annotation
+
+
+def resolve_annotation(annotations: dict[str, Any], arg_name: str):
+ """Resolve the annotation for the given argument name.
+
+ Args:
+ annotations: The annotations.
+ arg_name: The argument name.
+
+ Returns:
+ The resolved annotation.
+ """
+ annotation = annotations.get(arg_name)
+ if annotation is None:
+ console.deprecate(
+ feature_name="Unannotated event handler arguments",
+ reason="Provide type annotations for event handler arguments.",
+ deprecation_version="0.6.3",
+ removal_version="0.7.0",
+ )
+ # Allow arbitrary attribute access two levels deep until removed.
+ return Dict[str, dict]
+ return annotation
+
+
+def parse_args_spec(arg_spec: ArgsSpec | Sequence[ArgsSpec]):
"""Parse the args provided in the ArgsSpec of an event trigger.
Args:
@@ -811,68 +1242,105 @@ def parse_args_spec(arg_spec: ArgsSpec):
Returns:
The parsed args.
"""
+ # if there's multiple, the first is the default
+ arg_spec = arg_spec[0] if isinstance(arg_spec, Sequence) else arg_spec
spec = inspect.getfullargspec(arg_spec)
annotations = get_type_hints(arg_spec)
- return arg_spec(
- *[
- BaseVar(
- _var_name=f"_{l_arg}",
- _var_type=annotations.get(l_arg, FrontendEvent),
- _var_is_local=True,
- )
- for l_arg in spec.args
- ]
+
+ return list(
+ arg_spec(
+ *[
+ Var(f"_{l_arg}").to(
+ unwrap_var_annotation(resolve_annotation(annotations, l_arg))
+ )
+ for l_arg in spec.args
+ ]
+ )
)
-def call_event_fn(fn: Callable, arg: Union[Var, ArgsSpec]) -> list[EventSpec]:
+def check_fn_match_arg_spec(
+ fn: Callable,
+ arg_spec: ArgsSpec,
+ key: Optional[str] = None,
+) -> List[Var]:
+ """Ensures that the function signature matches the passed argument specification
+ or raises an EventFnArgMismatch if they do not.
+
+ Args:
+ fn: The function to be validated.
+ arg_spec: The argument specification for the event trigger.
+ key: The key to pass to the event handler.
+
+ Returns:
+ The parsed arguments from the argument specification.
+
+ Raises:
+ EventFnArgMismatch: Raised if the number of mandatory arguments do not match
+ """
+ fn_args = inspect.getfullargspec(fn).args
+ fn_defaults_args = inspect.getfullargspec(fn).defaults
+ n_fn_args = len(fn_args)
+ n_fn_defaults_args = len(fn_defaults_args) if fn_defaults_args else 0
+ if isinstance(fn, types.MethodType):
+ n_fn_args -= 1 # subtract 1 for bound self arg
+ parsed_args = parse_args_spec(arg_spec)
+ if not (n_fn_args - n_fn_defaults_args <= len(parsed_args) <= n_fn_args):
+ raise EventFnArgMismatch(
+ "The number of mandatory arguments accepted by "
+ f"{fn} ({n_fn_args - n_fn_defaults_args}) "
+ "does not match the arguments passed by the event trigger: "
+ f"{[str(v) for v in parsed_args]}\n"
+ "See https://reflex.dev/docs/events/event-arguments/"
+ )
+ return parsed_args
+
+
+def call_event_fn(
+ fn: Callable,
+ arg_spec: ArgsSpec,
+ key: Optional[str] = None,
+) -> list[EventSpec] | Var:
"""Call a function to a list of event specs.
- The function should return either a single EventSpec or a list of EventSpecs.
- If the function takes in an arg, the arg will be passed to the function.
- Otherwise, the function will be called with no args.
+ The function should return a single EventSpec, a list of EventSpecs, or a
+ single Var.
Args:
fn: The function to call.
- arg: The argument to pass to the function.
+ arg_spec: The argument spec for the event trigger.
+ key: The key to pass to the event handler.
Returns:
- The event specs from calling the function.
+ The event specs from calling the function or a Var.
Raises:
- EventHandlerValueError: If the lambda has an invalid signature.
+ EventHandlerValueError: If the lambda returns an unusable value.
"""
# Import here to avoid circular imports.
from reflex.event import EventHandler, EventSpec
from reflex.utils.exceptions import EventHandlerValueError
- # Get the args of the lambda.
- args = inspect.getfullargspec(fn).args
+ # Check that fn signature matches arg_spec
+ parsed_args = check_fn_match_arg_spec(fn, arg_spec, key=key)
- if isinstance(arg, ArgsSpec):
- out = fn(*parse_args_spec(arg)) # type: ignore
- else:
- # Call the lambda.
- if len(args) == 0:
- out = fn()
- elif len(args) == 1:
- out = fn(arg)
- else:
- raise EventHandlerValueError(f"Lambda {fn} must have 0 or 1 arguments.")
+ # Call the function with the parsed args.
+ out = fn(*parsed_args)
+
+ # If the function returns a Var, assume it's an EventChain and render it directly.
+ if isinstance(out, Var):
+ return out
# Convert the output to a list.
- if not isinstance(out, List):
+ if not isinstance(out, list):
out = [out]
# Convert any event specs to event specs.
events = []
for e in out:
- # Convert handlers to event specs.
if isinstance(e, EventHandler):
- if len(args) == 0:
- e = e()
- elif len(args) == 1:
- e = e(arg) # type: ignore
+ # An un-called EventHandler gets all of the args of the event trigger.
+ e = call_event_handler(e, arg_spec, key=key)
# Make sure the event spec is valid.
if not isinstance(e, EventSpec):
@@ -887,7 +1355,9 @@ def call_event_fn(fn: Callable, arg: Union[Var, ArgsSpec]) -> list[EventSpec]:
return events
-def get_handler_args(event_spec: EventSpec) -> tuple[tuple[Var, Var], ...]:
+def get_handler_args(
+ event_spec: EventSpec,
+) -> tuple[tuple[Var, Var], ...]:
"""Get the handler args for the given event spec.
Args:
@@ -913,6 +1383,9 @@ def fix_events(
token: The user token.
router_data: The optional router data to set in the event.
+ Raises:
+ ValueError: If the event type is not what was expected.
+
Returns:
The fixed events.
"""
@@ -936,9 +1409,10 @@ def fix_events(
# Otherwise, create an event from the event spec.
if isinstance(e, EventHandler):
e = e()
- assert isinstance(e, EventSpec), f"Unexpected event type, {type(e)}."
+ if not isinstance(e, EventSpec):
+ raise ValueError(f"Unexpected event type, {type(e)}.")
name = format.format_event_handler(e.handler)
- payload = {k._var_name: v._decode() for k, v in e.args} # type: ignore
+ payload = {k._js_expr: v._decode() for k, v in e.args} # type: ignore
# Filter router_data to reduce payload size
event_router_data = {
@@ -973,3 +1447,401 @@ def get_fn_signature(fn: Callable) -> inspect.Signature:
"state", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=Any
)
return signature.replace(parameters=(new_param, *signature.parameters.values()))
+
+
+class EventVar(ObjectVar, python_types=EventSpec):
+ """Base class for event vars."""
+
+
+@dataclasses.dataclass(
+ eq=False,
+ frozen=True,
+ **{"slots": True} if sys.version_info >= (3, 10) else {},
+)
+class LiteralEventVar(VarOperationCall, LiteralVar, EventVar):
+ """A literal event var."""
+
+ _var_value: EventSpec = dataclasses.field(default=None) # type: ignore
+
+ def __hash__(self) -> int:
+ """Get the hash of the var.
+
+ Returns:
+ The hash of the var.
+ """
+ return hash((self.__class__.__name__, self._js_expr))
+
+ @classmethod
+ def create(
+ cls,
+ value: EventSpec,
+ _var_data: VarData | None = None,
+ ) -> LiteralEventVar:
+ """Create a new LiteralEventVar instance.
+
+ Args:
+ value: The value of the var.
+ _var_data: The data of the var.
+
+ Returns:
+ The created LiteralEventVar instance.
+ """
+ return cls(
+ _js_expr="",
+ _var_type=EventSpec,
+ _var_data=_var_data,
+ _var_value=value,
+ _func=FunctionStringVar("Event"),
+ _args=(
+ # event handler name
+ ".".join(
+ filter(
+ None,
+ format.get_event_handler_parts(value.handler),
+ )
+ ),
+ # event handler args
+ {str(name): value for name, value in value.args},
+ # event actions
+ value.event_actions,
+ # client handler name
+ *([value.client_handler_name] if value.client_handler_name else []),
+ ),
+ )
+
+
+class EventChainVar(FunctionVar, python_types=EventChain):
+ """Base class for event chain vars."""
+
+
+@dataclasses.dataclass(
+ eq=False,
+ frozen=True,
+ **{"slots": True} if sys.version_info >= (3, 10) else {},
+)
+# Note: LiteralVar is second in the inheritance list allowing it act like a
+# CachedVarOperation (ArgsFunctionOperation) and get the _js_expr from the
+# _cached_var_name property.
+class LiteralEventChainVar(ArgsFunctionOperation, LiteralVar, EventChainVar):
+ """A literal event chain var."""
+
+ _var_value: EventChain = dataclasses.field(default=None) # type: ignore
+
+ def __hash__(self) -> int:
+ """Get the hash of the var.
+
+ Returns:
+ The hash of the var.
+ """
+ return hash((self.__class__.__name__, self._js_expr))
+
+ @classmethod
+ def create(
+ cls,
+ value: EventChain,
+ _var_data: VarData | None = None,
+ ) -> LiteralEventChainVar:
+ """Create a new LiteralEventChainVar instance.
+
+ Args:
+ value: The value of the var.
+ _var_data: The data of the var.
+
+ Returns:
+ The created LiteralEventChainVar instance.
+ """
+ arg_spec = (
+ value.args_spec[0]
+ if isinstance(value.args_spec, Sequence)
+ else value.args_spec
+ )
+ sig = inspect.signature(arg_spec) # type: ignore
+ if sig.parameters:
+ arg_def = tuple((f"_{p}" for p in sig.parameters))
+ arg_def_expr = LiteralVar.create([Var(_js_expr=arg) for arg in arg_def])
+ else:
+ # add a default argument for addEvents if none were specified in value.args_spec
+ # used to trigger the preventDefault() on the event.
+ arg_def = ("...args",)
+ arg_def_expr = Var(_js_expr="args")
+
+ if value.invocation is None:
+ invocation = FunctionStringVar.create("addEvents")
+ else:
+ invocation = value.invocation
+
+ return cls(
+ _js_expr="",
+ _var_type=EventChain,
+ _var_data=_var_data,
+ _args_names=arg_def,
+ _return_expr=invocation.call(
+ LiteralVar.create([LiteralVar.create(event) for event in value.events]),
+ arg_def_expr,
+ value.event_actions,
+ ),
+ _var_value=value,
+ )
+
+
+P = ParamSpec("P")
+Q = ParamSpec("Q")
+T = TypeVar("T")
+V = TypeVar("V")
+V2 = TypeVar("V2")
+V3 = TypeVar("V3")
+V4 = TypeVar("V4")
+V5 = TypeVar("V5")
+
+background_event_decorator = background
+
+if sys.version_info >= (3, 10):
+ from typing import Concatenate
+
+ class EventCallback(Generic[P, T]):
+ """A descriptor that wraps a function to be used as an event."""
+
+ def __init__(self, func: Callable[Concatenate[Any, P], T]):
+ """Initialize the descriptor with the function to be wrapped.
+
+ Args:
+ func: The function to be wrapped.
+ """
+ self.func = func
+
+ @property
+ def prevent_default(self):
+ """Prevent default behavior.
+
+ Returns:
+ The event callback with prevent default behavior.
+ """
+ return self
+
+ @property
+ def stop_propagation(self):
+ """Stop event propagation.
+
+ Returns:
+ The event callback with stop propagation behavior.
+ """
+ return self
+
+ @overload
+ def __call__(
+ self: EventCallback[Q, T],
+ ) -> EventCallback[Q, T]: ...
+
+ @overload
+ def __call__(
+ self: EventCallback[Concatenate[V, Q], T], value: V | Var[V]
+ ) -> EventCallback[Q, T]: ...
+
+ @overload
+ def __call__(
+ self: EventCallback[Concatenate[V, V2, Q], T],
+ value: V | Var[V],
+ value2: V2 | Var[V2],
+ ) -> EventCallback[Q, T]: ...
+
+ @overload
+ def __call__(
+ self: EventCallback[Concatenate[V, V2, V3, Q], T],
+ value: V | Var[V],
+ value2: V2 | Var[V2],
+ value3: V3 | Var[V3],
+ ) -> EventCallback[Q, T]: ...
+
+ @overload
+ def __call__(
+ self: EventCallback[Concatenate[V, V2, V3, V4, Q], T],
+ value: V | Var[V],
+ value2: V2 | Var[V2],
+ value3: V3 | Var[V3],
+ value4: V4 | Var[V4],
+ ) -> EventCallback[Q, T]: ...
+
+ def __call__(self, *values) -> EventCallback: # type: ignore
+ """Call the function with the values.
+
+ Args:
+ *values: The values to call the function with.
+
+ Returns:
+ The function with the values.
+ """
+ return self.func(*values) # type: ignore
+
+ @overload
+ def __get__(
+ self: EventCallback[P, T], instance: None, owner
+ ) -> EventCallback[P, T]: ...
+
+ @overload
+ def __get__(self, instance, owner) -> Callable[P, T]: ...
+
+ def __get__(self, instance, owner) -> Callable: # type: ignore
+ """Get the function with the instance bound to it.
+
+ Args:
+ instance: The instance to bind to the function.
+ owner: The owner of the function.
+
+ Returns:
+ The function with the instance bound to it
+ """
+ if instance is None:
+ return self.func # type: ignore
+
+ return partial(self.func, instance) # type: ignore
+
+
+else:
+
+ class EventCallback(Generic[P, T]):
+ """A descriptor that wraps a function to be used as an event."""
+
+
+G = ParamSpec("G")
+
+IndividualEventType = Union[
+ EventSpec, EventHandler, Callable[G, Any], EventCallback[G, Any], Var[Any]
+]
+
+ItemOrList = Union[V, List[V]]
+
+EventType = ItemOrList[IndividualEventType[G]]
+
+
+class EventNamespace(types.SimpleNamespace):
+ """A namespace for event related classes."""
+
+ Event = Event
+ EventHandler = EventHandler
+ EventSpec = EventSpec
+ CallableEventSpec = CallableEventSpec
+ EventChain = EventChain
+ EventVar = EventVar
+ LiteralEventVar = LiteralEventVar
+ EventChainVar = EventChainVar
+ LiteralEventChainVar = LiteralEventChainVar
+ EventType = EventType
+ EventCallback = EventCallback
+
+ if sys.version_info >= (3, 10):
+
+ @overload
+ @staticmethod
+ def __call__(
+ func: None = None, *, background: bool | None = None
+ ) -> Callable[[Callable[Concatenate[Any, P], T]], EventCallback[P, T]]: ...
+
+ @overload
+ @staticmethod
+ def __call__(
+ func: Callable[Concatenate[Any, P], T],
+ *,
+ background: bool | None = None,
+ ) -> EventCallback[P, T]: ...
+
+ @staticmethod
+ def __call__(
+ func: Callable[Concatenate[Any, P], T] | None = None,
+ *,
+ background: bool | None = None,
+ ) -> Union[
+ EventCallback[P, T],
+ Callable[[Callable[Concatenate[Any, P], T]], EventCallback[P, T]],
+ ]:
+ """Wrap a function to be used as an event.
+
+ Args:
+ func: The function to wrap.
+ background: Whether the event should be run in the background. Defaults to False.
+
+ Returns:
+ The wrapped function.
+ """
+
+ def wrapper(func: Callable[Concatenate[Any, P], T]) -> EventCallback[P, T]:
+ if background is True:
+ return background_event_decorator(func, __internal_reflex_call=True) # type: ignore
+ return func # type: ignore
+
+ if func is not None:
+ return wrapper(func)
+ return wrapper
+ else:
+
+ @overload
+ @staticmethod
+ def __call__(
+ func: None = None, *, background: bool | None = None
+ ) -> Callable[[Callable[P, T]], Callable[P, T]]: ...
+
+ @overload
+ @staticmethod
+ def __call__(
+ func: Callable[P, T], *, background: bool | None = None
+ ) -> Callable[P, T]: ...
+
+ @staticmethod
+ def __call__(
+ func: Callable[P, T] | None = None,
+ *,
+ background: bool | None = None,
+ ) -> Union[
+ Callable[P, T],
+ Callable[[Callable[P, T]], Callable[P, T]],
+ ]:
+ """Wrap a function to be used as an event.
+
+ Args:
+ func: The function to wrap.
+ background: Whether the event should be run in the background. Defaults to False.
+
+ Returns:
+ The wrapped function.
+ """
+
+ def wrapper(func: Callable[P, T]) -> Callable[P, T]:
+ if background is True:
+ return background_event_decorator(func, __internal_reflex_call=True) # type: ignore
+ return func # type: ignore
+
+ if func is not None:
+ return wrapper(func)
+ return wrapper
+
+ get_event = staticmethod(get_event)
+ get_hydrate_event = staticmethod(get_hydrate_event)
+ fix_events = staticmethod(fix_events)
+ call_event_handler = staticmethod(call_event_handler)
+ call_event_fn = staticmethod(call_event_fn)
+ get_handler_args = staticmethod(get_handler_args)
+ check_fn_match_arg_spec = staticmethod(check_fn_match_arg_spec)
+ resolve_annotation = staticmethod(resolve_annotation)
+ parse_args_spec = staticmethod(parse_args_spec)
+ identity_event = staticmethod(identity_event)
+ input_event = staticmethod(input_event)
+ key_event = staticmethod(key_event)
+ empty_event = staticmethod(empty_event)
+ server_side = staticmethod(server_side)
+ redirect = staticmethod(redirect)
+ console_log = staticmethod(console_log)
+ back = staticmethod(back)
+ window_alert = staticmethod(window_alert)
+ set_focus = staticmethod(set_focus)
+ scroll_to = staticmethod(scroll_to)
+ set_value = staticmethod(set_value)
+ remove_cookie = staticmethod(remove_cookie)
+ clear_local_storage = staticmethod(clear_local_storage)
+ remove_local_storage = staticmethod(remove_local_storage)
+ clear_session_storage = staticmethod(clear_session_storage)
+ remove_session_storage = staticmethod(remove_session_storage)
+ set_clipboard = staticmethod(set_clipboard)
+ download = staticmethod(download)
+ call_script = staticmethod(call_script)
+
+
+event = EventNamespace()
diff --git a/reflex/experimental/__init__.py b/reflex/experimental/__init__.py
index 991dffd50..164790fe5 100644
--- a/reflex/experimental/__init__.py
+++ b/reflex/experimental/__init__.py
@@ -2,11 +2,15 @@
from types import SimpleNamespace
+from reflex.components.datadisplay.shiki_code_block import code_block as code_block
+from reflex.components.props import PropsBase
from reflex.components.radix.themes.components.progress import progress as progress
from reflex.components.sonner.toast import toast as toast
from ..utils.console import warn
from . import hooks as hooks
+from .assets import asset as asset
+from .client_state import ClientStateVar as ClientStateVar
from .layout import layout as layout
from .misc import run_in_thread as run_in_thread
@@ -14,10 +18,55 @@ warn(
"`rx._x` contains experimental features and might be removed at any time in the future .",
)
-_x = SimpleNamespace(
+_EMITTED_PROMOTION_WARNINGS = set()
+
+
+class ExperimentalNamespace(SimpleNamespace):
+ """Namespace for experimental features."""
+
+ @property
+ def toast(self):
+ """Temporary property returning the toast namespace.
+
+ Remove this property when toast is fully promoted.
+
+ Returns:
+ The toast namespace.
+ """
+ self.register_component_warning("toast")
+ return toast
+
+ @property
+ def progress(self):
+ """Temporary property returning the toast namespace.
+
+ Remove this property when toast is fully promoted.
+
+ Returns:
+ The toast namespace.
+ """
+ self.register_component_warning("progress")
+ return progress
+
+ @staticmethod
+ def register_component_warning(component_name: str):
+ """Add component to emitted warnings and throw a warning if it
+ doesn't exist.
+
+ Args:
+ component_name: name of the component.
+ """
+ if component_name not in _EMITTED_PROMOTION_WARNINGS:
+ _EMITTED_PROMOTION_WARNINGS.add(component_name)
+ warn(f"`rx._x.{component_name}` was promoted to `rx.{component_name}`.")
+
+
+_x = ExperimentalNamespace(
+ asset=asset,
+ client_state=ClientStateVar.create,
hooks=hooks,
layout=layout,
- progress=progress,
+ PropsBase=PropsBase,
run_in_thread=run_in_thread,
- toast=toast,
+ code_block=code_block,
)
diff --git a/reflex/experimental/assets.py b/reflex/experimental/assets.py
new file mode 100644
index 000000000..dcf386d8d
--- /dev/null
+++ b/reflex/experimental/assets.py
@@ -0,0 +1,59 @@
+"""Helper functions for adding assets to the app."""
+
+import inspect
+from pathlib import Path
+from typing import Optional
+
+from reflex import constants
+
+
+def asset(relative_filename: str, subfolder: Optional[str] = None) -> str:
+ """Add an asset to the app.
+ Place the file next to your including python file.
+ Copies the file to the app's external assets directory.
+
+ Example:
+ ```python
+ rx.script(src=rx._x.asset("my_custom_javascript.js"))
+ rx.image(src=rx._x.asset("test_image.png","subfolder"))
+ ```
+
+ Args:
+ relative_filename: The relative filename of the asset.
+ subfolder: The directory to place the asset in.
+
+ Raises:
+ FileNotFoundError: If the file does not exist.
+ ValueError: If the module is None.
+
+ Returns:
+ The relative URL to the copied asset.
+ """
+ # Determine the file by which the asset is exposed.
+ calling_file = inspect.stack()[1].filename
+ module = inspect.getmodule(inspect.stack()[1][0])
+ if module is None:
+ raise ValueError("Module is None")
+ caller_module_path = module.__name__.replace(".", "/")
+
+ subfolder = f"{caller_module_path}/{subfolder}" if subfolder else caller_module_path
+
+ src_file = Path(calling_file).parent / relative_filename
+
+ assets = constants.Dirs.APP_ASSETS
+ external = constants.Dirs.EXTERNAL_APP_ASSETS
+
+ if not src_file.exists():
+ raise FileNotFoundError(f"File not found: {src_file}")
+
+ # Create the asset folder in the currently compiling app.
+ asset_folder = Path.cwd() / assets / external / subfolder
+ asset_folder.mkdir(parents=True, exist_ok=True)
+
+ dst_file = asset_folder / relative_filename
+
+ if not dst_file.exists():
+ dst_file.symlink_to(src_file)
+
+ asset_url = f"/{external}/{subfolder}/{relative_filename}"
+ return asset_url
diff --git a/reflex/experimental/client_state.py b/reflex/experimental/client_state.py
new file mode 100644
index 000000000..74a25c2cd
--- /dev/null
+++ b/reflex/experimental/client_state.py
@@ -0,0 +1,248 @@
+"""Handle client side state with `useState`."""
+
+from __future__ import annotations
+
+import dataclasses
+import re
+import sys
+from typing import Any, Callable, Union
+
+from reflex import constants
+from reflex.event import EventChain, EventHandler, EventSpec, call_script
+from reflex.utils.imports import ImportVar
+from reflex.vars import (
+ VarData,
+ get_unique_variable_name,
+)
+from reflex.vars.base import LiteralVar, Var
+from reflex.vars.function import FunctionVar
+
+NoValue = object()
+
+
+_refs_import = {
+ f"$/{constants.Dirs.STATE_PATH}": [ImportVar(tag="refs")],
+}
+
+
+def _client_state_ref(var_name: str) -> str:
+ """Get the ref path for a ClientStateVar.
+
+ Args:
+ var_name: The name of the variable.
+
+ Returns:
+ An accessor for ClientStateVar ref as a string.
+ """
+ return f"refs['_client_state_{var_name}']"
+
+
+@dataclasses.dataclass(
+ eq=False,
+ frozen=True,
+ **{"slots": True} if sys.version_info >= (3, 10) else {},
+)
+class ClientStateVar(Var):
+ """A Var that exists on the client via useState."""
+
+ # Track the names of the getters and setters
+ _setter_name: str = dataclasses.field(default="")
+ _getter_name: str = dataclasses.field(default="")
+
+ # Whether to add the var and setter to the global `refs` object for use in any Component.
+ _global_ref: bool = dataclasses.field(default=True)
+
+ def __hash__(self) -> int:
+ """Define a hash function for a var.
+
+ Returns:
+ The hash of the var.
+ """
+ return hash(
+ (self._js_expr, str(self._var_type), self._getter_name, self._setter_name)
+ )
+
+ @classmethod
+ def create(
+ cls,
+ var_name: str | None = None,
+ default: Any = NoValue,
+ global_ref: bool = True,
+ ) -> "ClientStateVar":
+ """Create a local_state Var that can be accessed and updated on the client.
+
+ The `ClientStateVar` should be included in the highest parent component
+ that contains the components which will access and manipulate the client
+ state. It has no visual rendering, including it ensures that the
+ `useState` hook is called in the correct scope.
+
+ To render the var in a component, use the `value` property.
+
+ To update the var in a component, use the `set` property or `set_value` method.
+
+ To access the var in an event handler, use the `retrieve` method with
+ `callback` set to the event handler which should receive the value.
+
+ To update the var in an event handler, use the `push` method with the
+ value to update.
+
+ Args:
+ var_name: The name of the variable.
+ default: The default value of the variable.
+ global_ref: Whether the state should be accessible in any Component and on the backend.
+
+ Raises:
+ ValueError: If the var_name is not a string.
+
+ Returns:
+ ClientStateVar
+ """
+ if var_name is None:
+ var_name = get_unique_variable_name()
+ if not isinstance(var_name, str):
+ raise ValueError("var_name must be a string.")
+ if default is NoValue:
+ default_var = Var(_js_expr="")
+ elif not isinstance(default, Var):
+ default_var = LiteralVar.create(default)
+ else:
+ default_var = default
+ setter_name = f"set{var_name.capitalize()}"
+ hooks = {
+ f"const [{var_name}, {setter_name}] = useState({str(default_var)})": None,
+ }
+ imports = {
+ "react": [ImportVar(tag="useState")],
+ }
+ if global_ref:
+ hooks[f"{_client_state_ref(var_name)} = {var_name}"] = None
+ hooks[f"{_client_state_ref(setter_name)} = {setter_name}"] = None
+ imports.update(_refs_import)
+ return cls(
+ _js_expr="",
+ _setter_name=setter_name,
+ _getter_name=var_name,
+ _global_ref=global_ref,
+ _var_type=default_var._var_type,
+ _var_data=VarData.merge(
+ default_var._var_data,
+ VarData(
+ hooks=hooks,
+ imports=imports,
+ ),
+ ),
+ )
+
+ @property
+ def value(self) -> Var:
+ """Get a placeholder for the Var.
+
+ This property can only be rendered on the frontend.
+
+ To access the value in a backend event handler, see `retrieve`.
+
+ Returns:
+ an accessor for the client state variable.
+ """
+ return (
+ Var(
+ _js_expr=(
+ _client_state_ref(self._getter_name)
+ if self._global_ref
+ else self._getter_name
+ )
+ )
+ .to(self._var_type)
+ ._replace(
+ merge_var_data=VarData( # type: ignore
+ imports=_refs_import if self._global_ref else {}
+ )
+ )
+ )
+
+ def set_value(self, value: Any = NoValue) -> Var:
+ """Set the value of the client state variable.
+
+ This property can only be attached to a frontend event trigger.
+
+ To set a value from a backend event handler, see `push`.
+
+ Args:
+ value: The value to set.
+
+ Returns:
+ A special EventChain Var which will set the value when triggered.
+ """
+ setter = (
+ _client_state_ref(self._setter_name)
+ if self._global_ref
+ else self._setter_name
+ )
+ _var_data = VarData(imports=_refs_import if self._global_ref else {})
+ if value is not NoValue:
+ # This is a hack to make it work like an EventSpec taking an arg
+ value_var = LiteralVar.create(value)
+ _var_data = VarData.merge(_var_data, value_var._get_all_var_data())
+ value_str = str(value_var)
+
+ if value_str.startswith("_"):
+ # remove patterns of ["*"] from the value_str using regex
+ arg = re.sub(r"\[\".*\"\]", "", value_str)
+ setter = f"(({arg}) => {setter}({value_str}))"
+ else:
+ setter = f"(() => {setter}({value_str}))"
+ return Var(
+ _js_expr=setter,
+ _var_data=_var_data,
+ ).to(FunctionVar, EventChain)
+
+ @property
+ def set(self) -> Var:
+ """Set the value of the client state variable.
+
+ This property can only be attached to a frontend event trigger.
+
+ To set a value from a backend event handler, see `push`.
+
+ Returns:
+ A special EventChain Var which will set the value when triggered.
+ """
+ return self.set_value()
+
+ def retrieve(
+ self, callback: Union[EventHandler, Callable, None] = None
+ ) -> EventSpec:
+ """Pass the value of the client state variable to a backend EventHandler.
+
+ The event handler must `yield` or `return` the EventSpec to trigger the event.
+
+ Args:
+ callback: The callback to pass the value to.
+
+ Returns:
+ An EventSpec which will retrieve the value when triggered.
+
+ Raises:
+ ValueError: If the ClientStateVar is not global.
+ """
+ if not self._global_ref:
+ raise ValueError("ClientStateVar must be global to retrieve the value.")
+ return call_script(_client_state_ref(self._getter_name), callback=callback)
+
+ def push(self, value: Any) -> EventSpec:
+ """Push a value to the client state variable from the backend.
+
+ The event handler must `yield` or `return` the EventSpec to trigger the event.
+
+ Args:
+ value: The value to update.
+
+ Returns:
+ An EventSpec which will push the value when triggered.
+
+ Raises:
+ ValueError: If the ClientStateVar is not global.
+ """
+ if not self._global_ref:
+ raise ValueError("ClientStateVar must be global to push the value.")
+ return call_script(f"{_client_state_ref(self._setter_name)}({value})")
diff --git a/reflex/experimental/hooks.py b/reflex/experimental/hooks.py
index 9040abd4d..7d648225a 100644
--- a/reflex/experimental/hooks.py
+++ b/reflex/experimental/hooks.py
@@ -1,22 +1,17 @@
"""Add standard Hooks wrapper for React."""
+from __future__ import annotations
+
from reflex.utils.imports import ImportVar
-from reflex.vars import Var, VarData
+from reflex.vars import VarData
+from reflex.vars.base import Var
-def _add_react_import(v: Var | None, tags: str | list):
- if v is None:
- return
-
- if isinstance(tags, str):
- tags = [tags]
-
- v._var_data = VarData( # type: ignore
- imports={"react": [ImportVar(tag=tag, install=False) for tag in tags]},
- )
+def _compose_react_imports(tags: list[str]) -> dict[str, list[ImportVar]]:
+ return {"react": [ImportVar(tag=tag) for tag in tags]}
-def const(name, value) -> Var | None:
+def const(name, value) -> Var:
"""Create a constant Var.
Args:
@@ -27,11 +22,11 @@ def const(name, value) -> Var | None:
The constant Var.
"""
if isinstance(name, list):
- return Var.create(f"const [{', '.join(name)}] = {value}")
- return Var.create(f"const {name} = {value}")
+ return Var(_js_expr=f"const [{', '.join(name)}] = {value}")
+ return Var(_js_expr=f"const {name} = {value}")
-def useCallback(func, deps) -> Var | None:
+def useCallback(func, deps) -> Var:
"""Create a useCallback hook with a function and dependencies.
Args:
@@ -41,15 +36,13 @@ def useCallback(func, deps) -> Var | None:
Returns:
The useCallback hook.
"""
- if deps:
- v = Var.create(f"useCallback({func}, {deps})")
- else:
- v = Var.create(f"useCallback({func})")
- _add_react_import(v, "useCallback")
- return v
+ return Var(
+ _js_expr=f"useCallback({func}, {deps})" if deps else f"useCallback({func})",
+ _var_data=VarData(imports=_compose_react_imports(["useCallback"])),
+ )
-def useContext(context) -> Var | None:
+def useContext(context) -> Var:
"""Create a useContext hook with a context.
Args:
@@ -58,12 +51,13 @@ def useContext(context) -> Var | None:
Returns:
The useContext hook.
"""
- v = Var.create(f"useContext({context})")
- _add_react_import(v, "useContext")
- return v
+ return Var(
+ _js_expr=f"useContext({context})",
+ _var_data=VarData(imports=_compose_react_imports(["useContext"])),
+ )
-def useRef(default) -> Var | None:
+def useRef(default) -> Var:
"""Create a useRef hook with a default value.
Args:
@@ -72,12 +66,13 @@ def useRef(default) -> Var | None:
Returns:
The useRef hook.
"""
- v = Var.create(f"useRef({default})")
- _add_react_import(v, "useRef")
- return v
+ return Var(
+ _js_expr=f"useRef({default})",
+ _var_data=VarData(imports=_compose_react_imports(["useRef"])),
+ )
-def useState(var_name, default=None) -> Var | None:
+def useState(var_name, default=None) -> Var:
"""Create a useState hook with a variable name and setter name.
Args:
@@ -87,7 +82,10 @@ def useState(var_name, default=None) -> Var | None:
Returns:
A useState hook.
"""
- setter_name = f"set{var_name.capitalize()}"
- v = const([var_name, setter_name], f"useState({default})")
- _add_react_import(v, "useState")
- return v
+ return const(
+ [var_name, f"set{var_name.capitalize()}"],
+ Var(
+ _js_expr=f"useState({default})",
+ _var_data=VarData(imports=_compose_react_imports(["useState"])),
+ ),
+ )
diff --git a/reflex/experimental/layout.py b/reflex/experimental/layout.py
index 5041b9356..a3b76581a 100644
--- a/reflex/experimental/layout.py
+++ b/reflex/experimental/layout.py
@@ -2,17 +2,21 @@
from __future__ import annotations
+from typing import Any, List
+
from reflex import color, cond
from reflex.components.base.fragment import Fragment
from reflex.components.component import Component, ComponentNamespace, MemoizationLeaf
from reflex.components.radix.primitives.drawer import DrawerRoot, drawer
from reflex.components.radix.themes.components.icon_button import IconButton
-from reflex.components.radix.themes.layout import Box, Container, HStack
+from reflex.components.radix.themes.layout.box import Box
+from reflex.components.radix.themes.layout.container import Container
+from reflex.components.radix.themes.layout.stack import HStack
from reflex.event import call_script
from reflex.experimental import hooks
from reflex.state import ComponentState
from reflex.style import Style
-from reflex.vars import Var
+from reflex.vars.base import Var
class Sidebar(Box, MemoizationLeaf):
@@ -40,7 +44,7 @@ class Sidebar(Box, MemoizationLeaf):
Box.create(width=props.get("width")), # spacer for layout
)
- def add_style(self) -> Style | None:
+ def add_style(self) -> dict[str, Any] | None:
"""Add style to the component.
Returns:
@@ -48,7 +52,11 @@ class Sidebar(Box, MemoizationLeaf):
"""
sidebar: Component = self.children[-2] # type: ignore
spacer: Component = self.children[-1] # type: ignore
- open = self.State.open if self.State else Var.create("open") # type: ignore
+ open = (
+ self.State.open # type: ignore
+ if self.State
+ else Var(_js_expr="open")
+ )
sidebar.style["display"] = spacer.style["display"] = cond(open, "block", "none")
return Style(
@@ -61,8 +69,13 @@ class Sidebar(Box, MemoizationLeaf):
}
)
- def _get_hooks(self) -> Var | None:
- return hooks.useState("open", "true") if not self.State else None
+ def add_hooks(self) -> List[Var]:
+ """Get the hooks to render.
+
+ Returns:
+ The hooks for the sidebar.
+ """
+ return [hooks.useState("open", "true")] if not self.State else []
class StatefulSidebar(ComponentState):
@@ -158,7 +171,10 @@ class SidebarTrigger(Fragment):
if sidebar.State:
open, toggle = sidebar.State.open, sidebar.State.toggle # type: ignore
else:
- open, toggle = Var.create("open"), call_script(Var.create("setOpen(!open)")) # type: ignore
+ open, toggle = (
+ Var(_js_expr="open"),
+ call_script(Var(_js_expr="setOpen(!open)")),
+ )
trigger_props["left"] = cond(open, f"calc({sidebar_width} - 32px)", "0")
diff --git a/reflex/experimental/layout.pyi b/reflex/experimental/layout.pyi
new file mode 100644
index 000000000..dcdac5b5d
--- /dev/null
+++ b/reflex/experimental/layout.pyi
@@ -0,0 +1,330 @@
+"""Stub file for reflex/experimental/layout.py"""
+
+# ------------------- DO NOT EDIT ----------------------
+# This file was generated by `reflex/utils/pyi_generator.py`!
+# ------------------------------------------------------
+from typing import Any, Dict, List, Literal, Optional, Union, overload
+
+from reflex import color
+from reflex.components.base.fragment import Fragment
+from reflex.components.component import Component, ComponentNamespace, MemoizationLeaf
+from reflex.components.radix.primitives.drawer import DrawerRoot
+from reflex.components.radix.themes.layout.box import Box
+from reflex.event import EventType
+from reflex.state import ComponentState
+from reflex.style import Style
+from reflex.vars.base import Var
+
+class Sidebar(Box, MemoizationLeaf):
+ @overload
+ @classmethod
+ def create( # type: ignore
+ cls,
+ *children,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ auto_capitalize: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ content_editable: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ context_menu: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ enter_key_hint: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ style: Optional[Style] = None,
+ key: Optional[Any] = None,
+ id: Optional[Any] = None,
+ class_name: Optional[Any] = None,
+ autofocus: Optional[bool] = None,
+ custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
+ ) -> "Sidebar":
+ """Create the sidebar component.
+
+ Args:
+ children: The children components.
+ props: The properties of the sidebar.
+
+ Returns:
+ The sidebar component.
+ """
+ ...
+
+ def add_style(self) -> dict[str, Any] | None: ...
+ def add_hooks(self) -> List[Var]: ...
+
+class StatefulSidebar(ComponentState):
+ open: bool
+
+ def toggle(self): ...
+ @classmethod
+ def get_component(cls, *children, **props): ...
+
+class DrawerSidebar(DrawerRoot):
+ @overload
+ @classmethod
+ def create( # type: ignore
+ cls,
+ *children,
+ open: Optional[Union[Var[bool], bool]] = None,
+ should_scale_background: Optional[Union[Var[bool], bool]] = None,
+ close_threshold: Optional[Union[Var[float], float]] = None,
+ snap_points: Optional[List[Union[float, str]]] = None,
+ fade_from_index: Optional[Union[Var[int], int]] = None,
+ scroll_lock_timeout: Optional[Union[Var[int], int]] = None,
+ modal: Optional[Union[Var[bool], bool]] = None,
+ direction: Optional[
+ Union[
+ Literal["bottom", "left", "right", "top"],
+ Var[Literal["bottom", "left", "right", "top"]],
+ ]
+ ] = None,
+ preventScrollRestoration: Optional[Union[Var[bool], bool]] = None,
+ as_child: Optional[Union[Var[bool], bool]] = None,
+ style: Optional[Style] = None,
+ key: Optional[Any] = None,
+ id: Optional[Any] = None,
+ class_name: Optional[Any] = None,
+ autofocus: Optional[bool] = None,
+ custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_open_change: Optional[EventType[bool]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
+ ) -> "DrawerSidebar":
+ """Create the sidebar component.
+
+ Args:
+ children: The children components.
+ props: The properties of the sidebar.
+
+ Returns:
+ The drawer sidebar component.
+ """
+ ...
+
+sidebar_trigger_style = {
+ "position": "fixed",
+ "z_index": "15",
+ "color": color("accent", 12),
+ "background_color": "transparent",
+ "padding": "0",
+}
+
+class SidebarTrigger(Fragment):
+ @overload
+ @classmethod
+ def create( # type: ignore
+ cls,
+ *children,
+ style: Optional[Style] = None,
+ key: Optional[Any] = None,
+ id: Optional[Any] = None,
+ class_name: Optional[Any] = None,
+ autofocus: Optional[bool] = None,
+ custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
+ ) -> "SidebarTrigger":
+ """Create the sidebar trigger component.
+
+ Args:
+ sidebar: The sidebar component.
+ props: The properties of the sidebar trigger.
+
+ Returns:
+ The sidebar trigger component.
+ """
+ ...
+
+class Layout(Box):
+ @overload
+ @classmethod
+ def create( # type: ignore
+ cls,
+ *children,
+ sidebar: Optional[Component] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ auto_capitalize: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ content_editable: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ context_menu: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ enter_key_hint: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ style: Optional[Style] = None,
+ key: Optional[Any] = None,
+ id: Optional[Any] = None,
+ class_name: Optional[Any] = None,
+ autofocus: Optional[bool] = None,
+ custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
+ ) -> "Layout":
+ """Create the layout component.
+
+ Args:
+ content: The content component.
+ sidebar: The sidebar component.
+ props: The properties of the layout.
+
+ Returns:
+ The layout component.
+ """
+ ...
+
+class LayoutNamespace(ComponentNamespace):
+ drawer_sidebar = staticmethod(DrawerSidebar.create)
+ stateful_sidebar = staticmethod(StatefulSidebar.create)
+ sidebar = staticmethod(Sidebar.create)
+
+ @staticmethod
+ def __call__(
+ *children,
+ sidebar: Optional[Component] = None,
+ access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ auto_capitalize: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ content_editable: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ context_menu: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ enter_key_hint: Optional[
+ Union[Var[Union[bool, int, str]], bool, int, str]
+ ] = None,
+ hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
+ style: Optional[Style] = None,
+ key: Optional[Any] = None,
+ id: Optional[Any] = None,
+ class_name: Optional[Any] = None,
+ autofocus: Optional[bool] = None,
+ custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
+ on_blur: Optional[EventType[[]]] = None,
+ on_click: Optional[EventType[[]]] = None,
+ on_context_menu: Optional[EventType[[]]] = None,
+ on_double_click: Optional[EventType[[]]] = None,
+ on_focus: Optional[EventType[[]]] = None,
+ on_mount: Optional[EventType[[]]] = None,
+ on_mouse_down: Optional[EventType[[]]] = None,
+ on_mouse_enter: Optional[EventType[[]]] = None,
+ on_mouse_leave: Optional[EventType[[]]] = None,
+ on_mouse_move: Optional[EventType[[]]] = None,
+ on_mouse_out: Optional[EventType[[]]] = None,
+ on_mouse_over: Optional[EventType[[]]] = None,
+ on_mouse_up: Optional[EventType[[]]] = None,
+ on_scroll: Optional[EventType[[]]] = None,
+ on_unmount: Optional[EventType[[]]] = None,
+ **props,
+ ) -> "Layout":
+ """Create the layout component.
+
+ Args:
+ content: The content component.
+ sidebar: The sidebar component.
+ props: The properties of the layout.
+
+ Returns:
+ The layout component.
+ """
+ ...
+
+layout = LayoutNamespace()
diff --git a/reflex/experimental/misc.py b/reflex/experimental/misc.py
index fec0bb992..a2a5a0615 100644
--- a/reflex/experimental/misc.py
+++ b/reflex/experimental/misc.py
@@ -1,12 +1,23 @@
"""Miscellaneous functions for the experimental package."""
import asyncio
+from typing import Any
-async def run_in_thread(func):
+async def run_in_thread(func) -> Any:
"""Run a function in a separate thread.
+ To not block the UI event queue, run_in_thread must be inside inside a rx.event(background=True) decorated method.
+
Args:
- func (callable): The function to run.
+ func (callable): The non-async function to run.
+
+ Raises:
+ ValueError: If the function is an async function.
+
+ Returns:
+ Any: The return value of the function.
"""
- await asyncio.get_event_loop().run_in_executor(None, func)
+ if asyncio.coroutines.iscoroutinefunction(func):
+ raise ValueError("func must be a non-async function")
+ return await asyncio.get_event_loop().run_in_executor(None, func)
diff --git a/reflex/istate/data.py b/reflex/istate/data.py
new file mode 100644
index 000000000..9f6e3b3f4
--- /dev/null
+++ b/reflex/istate/data.py
@@ -0,0 +1,126 @@
+"""This module contains the dataclasses representing the router object."""
+
+import dataclasses
+from typing import Optional
+
+from reflex import constants
+from reflex.utils import format
+
+
+@dataclasses.dataclass(frozen=True)
+class HeaderData:
+ """An object containing headers data."""
+
+ host: str = ""
+ origin: str = ""
+ upgrade: str = ""
+ connection: str = ""
+ cookie: str = ""
+ pragma: str = ""
+ cache_control: str = ""
+ user_agent: str = ""
+ sec_websocket_version: str = ""
+ sec_websocket_key: str = ""
+ sec_websocket_extensions: str = ""
+ accept_encoding: str = ""
+ accept_language: str = ""
+
+ def __init__(self, router_data: Optional[dict] = None):
+ """Initalize the HeaderData object based on router_data.
+
+ Args:
+ router_data: the router_data dict.
+ """
+ if router_data:
+ for k, v in router_data.get(constants.RouteVar.HEADERS, {}).items():
+ object.__setattr__(self, format.to_snake_case(k), v)
+ else:
+ for k in dataclasses.fields(self):
+ object.__setattr__(self, k.name, "")
+
+
+@dataclasses.dataclass(frozen=True)
+class PageData:
+ """An object containing page data."""
+
+ host: str = "" # repeated with self.headers.origin (remove or keep the duplicate?)
+ path: str = ""
+ raw_path: str = ""
+ full_path: str = ""
+ full_raw_path: str = ""
+ params: dict = dataclasses.field(default_factory=dict)
+
+ def __init__(self, router_data: Optional[dict] = None):
+ """Initalize the PageData object based on router_data.
+
+ Args:
+ router_data: the router_data dict.
+ """
+ if router_data:
+ object.__setattr__(
+ self,
+ "host",
+ router_data.get(constants.RouteVar.HEADERS, {}).get("origin", ""),
+ )
+ object.__setattr__(
+ self, "path", router_data.get(constants.RouteVar.PATH, "")
+ )
+ object.__setattr__(
+ self, "raw_path", router_data.get(constants.RouteVar.ORIGIN, "")
+ )
+ object.__setattr__(self, "full_path", f"{self.host}{self.path}")
+ object.__setattr__(self, "full_raw_path", f"{self.host}{self.raw_path}")
+ object.__setattr__(
+ self, "params", router_data.get(constants.RouteVar.QUERY, {})
+ )
+ else:
+ object.__setattr__(self, "host", "")
+ object.__setattr__(self, "path", "")
+ object.__setattr__(self, "raw_path", "")
+ object.__setattr__(self, "full_path", "")
+ object.__setattr__(self, "full_raw_path", "")
+ object.__setattr__(self, "params", {})
+
+
+@dataclasses.dataclass(frozen=True, init=False)
+class SessionData:
+ """An object containing session data."""
+
+ client_token: str = ""
+ client_ip: str = ""
+ session_id: str = ""
+
+ def __init__(self, router_data: Optional[dict] = None):
+ """Initalize the SessionData object based on router_data.
+
+ Args:
+ router_data: the router_data dict.
+ """
+ if router_data:
+ client_token = router_data.get(constants.RouteVar.CLIENT_TOKEN, "")
+ client_ip = router_data.get(constants.RouteVar.CLIENT_IP, "")
+ session_id = router_data.get(constants.RouteVar.SESSION_ID, "")
+ else:
+ client_token = client_ip = session_id = ""
+ object.__setattr__(self, "client_token", client_token)
+ object.__setattr__(self, "client_ip", client_ip)
+ object.__setattr__(self, "session_id", session_id)
+
+
+@dataclasses.dataclass(frozen=True, init=False)
+class RouterData:
+ """An object containing RouterData."""
+
+ session: SessionData = dataclasses.field(default_factory=SessionData)
+ headers: HeaderData = dataclasses.field(default_factory=HeaderData)
+ page: PageData = dataclasses.field(default_factory=PageData)
+
+ def __init__(self, router_data: Optional[dict] = None):
+ """Initialize the RouterData object.
+
+ Args:
+ router_data: the router_data dict.
+ """
+ object.__setattr__(self, "session", SessionData(router_data))
+ object.__setattr__(self, "headers", HeaderData(router_data))
+ object.__setattr__(self, "page", PageData(router_data))
diff --git a/reflex/istate/dynamic.py b/reflex/istate/dynamic.py
new file mode 100644
index 000000000..e5da36c26
--- /dev/null
+++ b/reflex/istate/dynamic.py
@@ -0,0 +1,3 @@
+"""A container for dynamically generated states."""
+
+# This page intentionally left blank.
diff --git a/reflex/istate/storage.py b/reflex/istate/storage.py
new file mode 100644
index 000000000..85e21ffa7
--- /dev/null
+++ b/reflex/istate/storage.py
@@ -0,0 +1,144 @@
+"""Client-side storage classes for reflex state variables."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from reflex.utils import format
+
+
+class ClientStorageBase:
+ """Base class for client-side storage."""
+
+ def options(self) -> dict[str, Any]:
+ """Get the options for the storage.
+
+ Returns:
+ All set options for the storage (not None).
+ """
+ return {
+ format.to_camel_case(k): v for k, v in vars(self).items() if v is not None
+ }
+
+
+class Cookie(ClientStorageBase, str):
+ """Represents a state Var that is stored as a cookie in the browser."""
+
+ name: str | None
+ path: str
+ max_age: int | None
+ domain: str | None
+ secure: bool | None
+ same_site: str
+
+ def __new__(
+ cls,
+ object: Any = "",
+ encoding: str | None = None,
+ errors: str | None = None,
+ /,
+ name: str | None = None,
+ path: str = "/",
+ max_age: int | None = None,
+ domain: str | None = None,
+ secure: bool | None = None,
+ same_site: str = "lax",
+ ):
+ """Create a client-side Cookie (str).
+
+ Args:
+ object: The initial object.
+ encoding: The encoding to use.
+ errors: The error handling scheme to use.
+ name: The name of the cookie on the client side.
+ path: Cookie path. Use / as the path if the cookie should be accessible on all pages.
+ max_age: Relative max age of the cookie in seconds from when the client receives it.
+ domain: Domain for the cookie (sub.domain.com or .allsubdomains.com).
+ secure: Is the cookie only accessible through HTTPS?
+ same_site: Whether the cookie is sent with third party requests.
+ One of (true|false|none|lax|strict)
+
+ Returns:
+ The client-side Cookie object.
+
+ Note: expires (absolute Date) is not supported at this time.
+ """
+ if encoding or errors:
+ inst = super().__new__(cls, object, encoding or "utf-8", errors or "strict")
+ else:
+ inst = super().__new__(cls, object)
+ inst.name = name
+ inst.path = path
+ inst.max_age = max_age
+ inst.domain = domain
+ inst.secure = secure
+ inst.same_site = same_site
+ return inst
+
+
+class LocalStorage(ClientStorageBase, str):
+ """Represents a state Var that is stored in localStorage in the browser."""
+
+ name: str | None
+ sync: bool = False
+
+ def __new__(
+ cls,
+ object: Any = "",
+ encoding: str | None = None,
+ errors: str | None = None,
+ /,
+ name: str | None = None,
+ sync: bool = False,
+ ) -> "LocalStorage":
+ """Create a client-side localStorage (str).
+
+ Args:
+ object: The initial object.
+ encoding: The encoding to use.
+ errors: The error handling scheme to use.
+ name: The name of the storage key on the client side.
+ sync: Whether changes should be propagated to other tabs.
+
+ Returns:
+ The client-side localStorage object.
+ """
+ if encoding or errors:
+ inst = super().__new__(cls, object, encoding or "utf-8", errors or "strict")
+ else:
+ inst = super().__new__(cls, object)
+ inst.name = name
+ inst.sync = sync
+ return inst
+
+
+class SessionStorage(ClientStorageBase, str):
+ """Represents a state Var that is stored in sessionStorage in the browser."""
+
+ name: str | None
+
+ def __new__(
+ cls,
+ object: Any = "",
+ encoding: str | None = None,
+ errors: str | None = None,
+ /,
+ name: str | None = None,
+ ) -> "SessionStorage":
+ """Create a client-side sessionStorage (str).
+
+ Args:
+ object: The initial object.
+ encoding: The encoding to use.
+ errors: The error handling scheme to use
+ name: The name of the storage on the client side
+
+ Returns:
+ The client-side sessionStorage object.
+ """
+ if encoding or errors:
+ inst = super().__new__(cls, object, encoding or "utf-8", errors or "strict")
+ else:
+ inst = super().__new__(cls, object)
+ inst.name = name
+ return inst
diff --git a/reflex/middleware/hydrate_middleware.py b/reflex/middleware/hydrate_middleware.py
index b1617fca7..2198b82c2 100644
--- a/reflex/middleware/hydrate_middleware.py
+++ b/reflex/middleware/hydrate_middleware.py
@@ -1,18 +1,20 @@
"""Middleware to hydrate the state."""
+
from __future__ import annotations
+import dataclasses
from typing import TYPE_CHECKING, Optional
from reflex import constants
from reflex.event import Event, get_hydrate_event
from reflex.middleware.middleware import Middleware
from reflex.state import BaseState, StateUpdate
-from reflex.utils import format
if TYPE_CHECKING:
from reflex.app import App
+@dataclasses.dataclass(init=True)
class HydrateMiddleware(Middleware):
"""Middleware to handle initial app hydration."""
@@ -40,7 +42,7 @@ class HydrateMiddleware(Middleware):
setattr(state, constants.CompileVars.IS_HYDRATED, False)
# Get the initial state.
- delta = format.format_state(state.dict())
+ delta = state.dict()
# since a full dict was captured, clean any dirtiness
state._clean()
diff --git a/reflex/middleware/middleware.py b/reflex/middleware/middleware.py
index f522ff861..ef9de0bde 100644
--- a/reflex/middleware/middleware.py
+++ b/reflex/middleware/middleware.py
@@ -1,10 +1,10 @@
"""Base Reflex middleware."""
+
from __future__ import annotations
-from abc import ABC
+from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Optional
-from reflex.base import Base
from reflex.event import Event
from reflex.state import BaseState, StateUpdate
@@ -12,9 +12,10 @@ if TYPE_CHECKING:
from reflex.app import App
-class Middleware(Base, ABC):
+class Middleware(ABC):
"""Middleware to preprocess and postprocess requests."""
+ @abstractmethod
async def preprocess(
self, app: App, state: BaseState, event: Event
) -> Optional[StateUpdate]:
diff --git a/reflex/model.py b/reflex/model.py
index 088601cae..5f5e8647d 100644
--- a/reflex/model.py
+++ b/reflex/model.py
@@ -2,9 +2,7 @@
from __future__ import annotations
-import os
from collections import defaultdict
-from pathlib import Path
from typing import Any, ClassVar, Optional, Type, Union
import alembic.autogenerate
@@ -15,16 +13,16 @@ import alembic.runtime.environment
import alembic.script
import alembic.util
import sqlalchemy
+import sqlalchemy.exc
import sqlalchemy.orm
-from reflex import constants
from reflex.base import Base
-from reflex.config import get_config
+from reflex.config import environment, get_config
from reflex.utils import console
-from reflex.utils.compat import sqlmodel
+from reflex.utils.compat import sqlmodel, sqlmodel_field_has_primary_key
-def get_engine(url: str | None = None):
+def get_engine(url: str | None = None) -> sqlalchemy.engine.Engine:
"""Get the database engine.
Args:
@@ -40,17 +38,38 @@ def get_engine(url: str | None = None):
url = url or conf.db_url
if url is None:
raise ValueError("No database url configured")
- if not Path(constants.ALEMBIC_CONFIG).exists():
+ if not environment.ALEMBIC_CONFIG.exists():
console.warn(
"Database is not initialized, run [bold]reflex db init[/bold] first."
)
# Print the SQL queries if the log level is INFO or lower.
- echo_db_query = os.environ.get("SQLALCHEMY_ECHO") == "True"
+ echo_db_query = environment.SQLALCHEMY_ECHO
# Needed for the admin dash on sqlite.
connect_args = {"check_same_thread": False} if url.startswith("sqlite") else {}
return sqlmodel.create_engine(url, echo=echo_db_query, connect_args=connect_args)
+async def get_db_status() -> bool:
+ """Checks the status of the database connection.
+
+ Attempts to connect to the database and execute a simple query to verify connectivity.
+
+ Returns:
+ bool: The status of the database connection:
+ - True: The database is accessible.
+ - False: The database is not accessible.
+ """
+ status = True
+ try:
+ engine = get_engine()
+ with engine.connect() as connection:
+ connection.execute(sqlalchemy.text("SELECT 1"))
+ except sqlalchemy.exc.OperationalError:
+ status = False
+
+ return status
+
+
SQLModelOrSqlAlchemy = Union[
Type[sqlmodel.SQLModel], Type[sqlalchemy.orm.DeclarativeBase]
]
@@ -144,8 +163,7 @@ class Model(Base, sqlmodel.SQLModel): # pyright: ignore [reportGeneralTypeIssue
non_default_primary_key_fields = [
field_name
for field_name, field in cls.__fields__.items()
- if field_name != "id"
- and getattr(field.field_info, "primary_key", None) is True
+ if field_name != "id" and sqlmodel_field_has_primary_key(field)
]
if non_default_primary_key_fields:
cls.__fields__.pop("id", None)
@@ -213,7 +231,7 @@ class Model(Base, sqlmodel.SQLModel): # pyright: ignore [reportGeneralTypeIssue
Returns:
tuple of (config, script_directory)
"""
- config = alembic.config.Config(constants.ALEMBIC_CONFIG)
+ config = alembic.config.Config(environment.ALEMBIC_CONFIG)
return config, alembic.script.ScriptDirectory(
config.get_main_option("script_location", default="version"),
)
@@ -248,8 +266,8 @@ class Model(Base, sqlmodel.SQLModel): # pyright: ignore [reportGeneralTypeIssue
def alembic_init(cls):
"""Initialize alembic for the project."""
alembic.command.init(
- config=alembic.config.Config(constants.ALEMBIC_CONFIG),
- directory=str(Path(constants.ALEMBIC_CONFIG).parent / "alembic"),
+ config=alembic.config.Config(environment.ALEMBIC_CONFIG),
+ directory=str(environment.ALEMBIC_CONFIG.parent / "alembic"),
)
@classmethod
@@ -269,7 +287,7 @@ class Model(Base, sqlmodel.SQLModel): # pyright: ignore [reportGeneralTypeIssue
Returns:
True when changes have been detected.
"""
- if not Path(constants.ALEMBIC_CONFIG).exists():
+ if not environment.ALEMBIC_CONFIG.exists():
return False
config, script_directory = cls._alembic_config()
@@ -370,7 +388,7 @@ class Model(Base, sqlmodel.SQLModel): # pyright: ignore [reportGeneralTypeIssue
True - indicating the process was successful.
None - indicating the process was skipped.
"""
- if not Path(constants.ALEMBIC_CONFIG).exists():
+ if not environment.ALEMBIC_CONFIG.exists():
return
with cls.get_db_engine().connect() as connection:
@@ -396,7 +414,7 @@ ModelRegistry.register(Model)
def session(url: str | None = None) -> sqlmodel.Session:
- """Get a session to interact with the database.
+ """Get a sqlmodel session to interact with the database.
Args:
url: The database url.
@@ -405,3 +423,15 @@ def session(url: str | None = None) -> sqlmodel.Session:
A database session.
"""
return sqlmodel.Session(get_engine(url))
+
+
+def sqla_session(url: str | None = None) -> sqlalchemy.orm.Session:
+ """Get a bare sqlalchemy session to interact with the database.
+
+ Args:
+ url: The database url.
+
+ Returns:
+ A database session.
+ """
+ return sqlalchemy.orm.Session(get_engine(url))
diff --git a/reflex/page.py b/reflex/page.py
index 1e5e8603d..87a8c49c2 100644
--- a/reflex/page.py
+++ b/reflex/page.py
@@ -6,6 +6,7 @@ from collections import defaultdict
from typing import Any, Dict, List
from reflex.config import get_config
+from reflex.event import EventType
DECORATED_PAGES: Dict[str, List] = defaultdict(list)
@@ -17,7 +18,7 @@ def page(
description: str | None = None,
meta: list[Any] | None = None,
script_tags: list[Any] | None = None,
- on_load: Any | list[Any] | None = None,
+ on_load: EventType[[]] | None = None,
):
"""Decorate a function as a page.
@@ -65,13 +66,20 @@ def page(
return decorator
-def get_decorated_pages() -> list[dict]:
+def get_decorated_pages(omit_implicit_routes=True) -> list[dict[str, Any]]:
"""Get the decorated pages.
+ Args:
+ omit_implicit_routes: Whether to omit pages where the route will be implicitely guessed later.
+
Returns:
The decorated pages.
"""
return sorted(
- [page_data for _, page_data in DECORATED_PAGES[get_config().app_name]],
- key=lambda x: x["route"],
+ [
+ page_data
+ for _, page_data in DECORATED_PAGES[get_config().app_name]
+ if not omit_implicit_routes or "route" in page_data
+ ],
+ key=lambda x: x.get("route", ""),
)
diff --git a/reflex/proxy.py b/reflex/proxy.py
index c47203bfd..7fbbcd444 100644
--- a/reflex/proxy.py
+++ b/reflex/proxy.py
@@ -51,14 +51,14 @@ else:
@asynccontextmanager
async def proxy_middleware( # pyright: ignore[reportGeneralTypeIssues]
- api: FastAPI,
+ app: FastAPI,
) -> AsyncGenerator[None, None]:
"""A middleware to proxy requests to the separate frontend server.
The proxy is installed on the / endpoint of the FastAPI instance.
Args:
- api: The FastAPI instance.
+ app: The FastAPI instance.
Yields:
None
@@ -67,7 +67,7 @@ else:
backend_port = config.backend_port
frontend_host = f"http://localhost:{config.frontend_port}"
proxy_context, proxy_app = _get_proxy_app_with_context(frontend_host)
- api.mount("/", proxy_app)
+ app.mount("/", proxy_app)
console.debug(
f"Proxying '/' requests on port {backend_port} to {frontend_host}"
)
diff --git a/reflex/reflex.py b/reflex/reflex.py
index 010cceaeb..7bef8b7e5 100644
--- a/reflex/reflex.py
+++ b/reflex/reflex.py
@@ -4,7 +4,6 @@ from __future__ import annotations
import atexit
import os
-import webbrowser
from pathlib import Path
from typing import List, Optional
@@ -14,9 +13,10 @@ from reflex_cli.deployments import deployments_cli
from reflex_cli.utils import dependency
from reflex import constants
-from reflex.config import get_config
+from reflex.config import environment, get_config
from reflex.custom_components.custom_components import custom_components_cli
-from reflex.utils import console, telemetry
+from reflex.state import reset_disk_state_manager
+from reflex.utils import console, redir, telemetry
# Disable typer+rich integration for help panels
typer.core.rich = False # type: ignore
@@ -65,6 +65,7 @@ def _init(
name: str,
template: str | None = None,
loglevel: constants.LogLevel = config.loglevel,
+ ai: bool = False,
):
"""Initialize a new Reflex app in the given directory."""
from reflex.utils import exec, prerequisites
@@ -84,18 +85,33 @@ def _init(
prerequisites.initialize_reflex_user_directory()
prerequisites.ensure_reflex_installation_id()
- # When upgrading to 0.4, show migration instructions.
- if prerequisites.should_show_rx_chakra_migration_instructions():
- prerequisites.show_rx_chakra_migration_instructions()
-
# Set up the web project.
prerequisites.initialize_frontend_dependencies()
+ # Integrate with reflex.build.
+ generation_hash = None
+ if ai:
+ if template is None:
+ # If AI is requested and no template specified, redirect the user to reflex.build.
+ generation_hash = redir.reflex_build_redirect()
+ elif prerequisites.is_generation_hash(template):
+ # Otherwise treat the template as a generation hash.
+ generation_hash = template
+ else:
+ console.error(
+ "Cannot use `--template` option with `--ai` option. Please remove `--template` option."
+ )
+ raise typer.Exit(2)
+ template = constants.Templates.DEFAULT
+
# Initialize the app.
prerequisites.initialize_app(app_name, template)
- # Migrate Pynecone projects to Reflex.
- prerequisites.migrate_to_reflex()
+ # If a reflex.build generation hash is available, download the code and apply it to the main module.
+ if generation_hash:
+ prerequisites.initialize_main_module_index_from_generation(
+ app_name, generation_hash=generation_hash
+ )
# Initialize the .gitignore.
prerequisites.initialize_gitignore()
@@ -119,9 +135,13 @@ def init(
loglevel: constants.LogLevel = typer.Option(
config.loglevel, help="The log level to use."
),
+ ai: bool = typer.Option(
+ False,
+ help="Use AI to create the initial template. Cannot be used with existing app or `--template` option.",
+ ),
):
"""Initialize a new Reflex app in the current directory."""
- _init(name, template, loglevel)
+ _init(name, template, loglevel, ai)
def _run(
@@ -157,12 +177,19 @@ def _run(
if prerequisites.needs_reinit(frontend=frontend):
_init(name=config.app_name, loglevel=loglevel)
- # Find the next available open port.
- if frontend and processes.is_process_on_port(frontend_port):
- frontend_port = processes.change_port(frontend_port, "frontend")
+ # Delete the states folder if it exists.
+ reset_disk_state_manager()
- if backend and processes.is_process_on_port(backend_port):
- backend_port = processes.change_port(backend_port, "backend")
+ # Find the next available open port if applicable.
+ if frontend:
+ frontend_port = processes.handle_port(
+ "frontend", frontend_port, str(constants.DefaultPorts.FRONTEND_PORT)
+ )
+
+ if backend:
+ backend_port = processes.handle_port(
+ "backend", backend_port, str(constants.DefaultPorts.BACKEND_PORT)
+ )
# Apply the new ports to the config.
if frontend_port != str(config.frontend_port):
@@ -198,7 +225,8 @@ def _run(
exec.run_frontend_prod,
exec.run_backend_prod,
)
- assert setup_frontend and frontend_cmd and backend_cmd, "Invalid env"
+ if not setup_frontend or not frontend_cmd or not backend_cmd:
+ raise ValueError("Invalid env")
# Post a telemetry event.
telemetry.send(f"run-{env.value}")
@@ -216,13 +244,23 @@ def _run(
# In prod mode, run the backend on a separate thread.
if backend and env == constants.Env.PROD:
- commands.append((backend_cmd, backend_host, backend_port))
+ commands.append(
+ (
+ backend_cmd,
+ backend_host,
+ backend_port,
+ loglevel.subprocess_level(),
+ frontend,
+ )
+ )
# Start the frontend and backend.
with processes.run_concurrently_context(*commands):
# In dev mode, run the backend on the main thread.
if backend and env == constants.Env.DEV:
- backend_cmd(backend_host, int(backend_port))
+ backend_cmd(
+ backend_host, int(backend_port), loglevel.subprocess_level(), frontend
+ )
# The windows uvicorn bug workaround
# https://github.com/reflex-dev/reflex/issues/2335
if constants.IS_WINDOWS and exec.frontend_process:
@@ -236,9 +274,17 @@ def run(
constants.Env.DEV, help="The environment to run the app in."
),
frontend: bool = typer.Option(
- False, "--frontend-only", help="Execute only frontend."
+ False,
+ "--frontend-only",
+ help="Execute only frontend.",
+ envvar=constants.ENV_FRONTEND_ONLY_ENV_VAR,
+ ),
+ backend: bool = typer.Option(
+ False,
+ "--backend-only",
+ help="Execute only backend.",
+ envvar=constants.ENV_BACKEND_ONLY_ENV_VAR,
),
- backend: bool = typer.Option(False, "--backend-only", help="Execute only backend."),
frontend_port: str = typer.Option(
config.frontend_port, help="Specify a different frontend port."
),
@@ -253,6 +299,12 @@ def run(
),
):
"""Run the app in the current directory."""
+ if frontend and backend:
+ console.error("Cannot use both --frontend-only and --backend-only options.")
+ raise typer.Exit(1)
+ os.environ[constants.ENV_BACKEND_ONLY_ENV_VAR] = str(backend).lower()
+ os.environ[constants.ENV_FRONTEND_ONLY_ENV_VAR] = str(frontend).lower()
+
_run(env, frontend, backend, frontend_port, backend_port, backend_host, loglevel)
@@ -294,7 +346,7 @@ def export(
backend=backend,
zip_dest_dir=zip_dest_dir,
upload_db_file=upload_db_file,
- loglevel=loglevel,
+ loglevel=loglevel.subprocess_level(),
)
@@ -368,7 +420,7 @@ def db_init():
return
# Check the alembic config.
- if Path(constants.ALEMBIC_CONFIG).exists():
+ if environment.ALEMBIC_CONFIG.exists():
console.error(
"Database is already initialized. Use "
"[bold]reflex db makemigrations[/bold] to create schema change "
@@ -427,17 +479,6 @@ def makemigrations(
)
-@script_cli.command(
- name="keep-chakra",
- help="Change all rx. references to rx.chakra., to preserve Chakra UI usage.",
-)
-def keep_chakra():
- """Change all rx. references to rx.chakra., to preserve Chakra UI usage."""
- from reflex.utils import prerequisites
-
- prerequisites.migrate_to_rx_chakra()
-
-
@cli.command()
def deploy(
key: Optional[str] = typer.Option(
@@ -540,7 +581,7 @@ def deploy(
frontend=frontend,
backend=backend,
zipping=zipping,
- loglevel=loglevel,
+ loglevel=loglevel.subprocess_level(),
upload_db_file=upload_db_file,
),
key=key,
@@ -554,22 +595,10 @@ def deploy(
interactive=interactive,
with_metrics=with_metrics,
with_tracing=with_tracing,
- loglevel=loglevel.value,
+ loglevel=loglevel.subprocess_level(),
)
-@cli.command()
-def demo(
- frontend_port: str = typer.Option(
- "3001", help="Specify a different frontend port."
- ),
- backend_port: str = typer.Option("8001", help="Specify a different backend port."),
-):
- """Run the demo app."""
- # Open the demo app in a terminal.
- webbrowser.open("https://demo.reflex.run")
-
-
cli.add_typer(db_cli, name="db", help="Subcommands for managing the database schema.")
cli.add_typer(script_cli, name="script", help="Subcommands running helper scripts.")
cli.add_typer(
diff --git a/reflex/state.py b/reflex/state.py
index ebe33aa26..cc9dda05b 100644
--- a/reflex/state.py
+++ b/reflex/state.py
@@ -5,17 +5,22 @@ from __future__ import annotations
import asyncio
import contextlib
import copy
+import dataclasses
import functools
import inspect
-import traceback
+import pickle
+import sys
import uuid
from abc import ABC, abstractmethod
from collections import defaultdict
+from hashlib import md5
+from pathlib import Path
from types import FunctionType, MethodType
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
+ BinaryIO,
Callable,
ClassVar,
Dict,
@@ -23,10 +28,33 @@ from typing import (
Optional,
Sequence,
Set,
+ Tuple,
Type,
+ TypeVar,
+ Union,
+ cast,
+ get_args,
+ get_type_hints,
)
-import dill
+from sqlalchemy.orm import DeclarativeBase
+from typing_extensions import Self
+
+from reflex import event
+from reflex.config import get_config
+from reflex.istate.data import RouterData
+from reflex.istate.storage import (
+ ClientStorageBase,
+)
+from reflex.vars.base import (
+ ComputedVar,
+ DynamicRouteVar,
+ Var,
+ computed_var,
+ dispatch,
+ get_unique_variable_name,
+ is_computed_var,
+)
try:
import pydantic.v1 as pydantic
@@ -35,22 +63,36 @@ except ModuleNotFoundError:
import wrapt
from redis.asyncio import Redis
+from redis.exceptions import ResponseError
+import reflex.istate.dynamic
from reflex import constants
from reflex.base import Base
+from reflex.config import environment
from reflex.event import (
BACKGROUND_TASK_MARKER,
Event,
EventHandler,
EventSpec,
fix_events,
- window_alert,
)
-from reflex.utils import console, format, prerequisites, types
-from reflex.utils.exceptions import ImmutableStateError, LockExpiredError
+from reflex.utils import console, format, path_ops, prerequisites, types
+from reflex.utils.exceptions import (
+ ComputedVarShadowsBaseVars,
+ ComputedVarShadowsStateVar,
+ DynamicComponentInvalidSignature,
+ DynamicRouteArgShadowsStateVar,
+ EventHandlerShadowsBuiltInStateMethod,
+ ImmutableStateError,
+ InvalidStateManagerMode,
+ LockExpiredError,
+ SetUndefinedStateVarError,
+ StateSchemaMismatchError,
+)
from reflex.utils.exec import is_testing_env
-from reflex.utils.serializers import SerializedType, serialize, serializer
-from reflex.vars import BaseVar, ComputedVar, Var, computed_var
+from reflex.utils.serializers import serializer
+from reflex.utils.types import _isinstance, get_origin, override
+from reflex.vars import VarData
if TYPE_CHECKING:
from reflex.components.component import Component
@@ -63,98 +105,14 @@ var = computed_var
# If the state is this large, it's considered a performance issue.
TOO_LARGE_SERIALIZED_STATE = 100 * 1024 # 100kb
-
-class HeaderData(Base):
- """An object containing headers data."""
-
- host: str = ""
- origin: str = ""
- upgrade: str = ""
- connection: str = ""
- pragma: str = ""
- cache_control: str = ""
- user_agent: str = ""
- sec_websocket_version: str = ""
- sec_websocket_key: str = ""
- sec_websocket_extensions: str = ""
- accept_encoding: str = ""
- accept_language: str = ""
-
- def __init__(self, router_data: Optional[dict] = None):
- """Initalize the HeaderData object based on router_data.
-
- Args:
- router_data: the router_data dict.
- """
- super().__init__()
- if router_data:
- for k, v in router_data.get(constants.RouteVar.HEADERS, {}).items():
- setattr(self, format.to_snake_case(k), v)
-
-
-class PageData(Base):
- """An object containing page data."""
-
- host: str = "" # repeated with self.headers.origin (remove or keep the duplicate?)
- path: str = ""
- raw_path: str = ""
- full_path: str = ""
- full_raw_path: str = ""
- params: dict = {}
-
- def __init__(self, router_data: Optional[dict] = None):
- """Initalize the PageData object based on router_data.
-
- Args:
- router_data: the router_data dict.
- """
- super().__init__()
- if router_data:
- self.host = router_data.get(constants.RouteVar.HEADERS, {}).get("origin")
- self.path = router_data.get(constants.RouteVar.PATH, "")
- self.raw_path = router_data.get(constants.RouteVar.ORIGIN, "")
- self.full_path = f"{self.host}{self.path}"
- self.full_raw_path = f"{self.host}{self.raw_path}"
- self.params = router_data.get(constants.RouteVar.QUERY, {})
-
-
-class SessionData(Base):
- """An object containing session data."""
-
- client_token: str = ""
- client_ip: str = ""
- session_id: str = ""
-
- def __init__(self, router_data: Optional[dict] = None):
- """Initalize the SessionData object based on router_data.
-
- Args:
- router_data: the router_data dict.
- """
- super().__init__()
- if router_data:
- self.client_token = router_data.get(constants.RouteVar.CLIENT_TOKEN, "")
- self.client_ip = router_data.get(constants.RouteVar.CLIENT_IP, "")
- self.session_id = router_data.get(constants.RouteVar.SESSION_ID, "")
-
-
-class RouterData(Base):
- """An object containing RouterData."""
-
- session: SessionData = SessionData()
- headers: HeaderData = HeaderData()
- page: PageData = PageData()
-
- def __init__(self, router_data: Optional[dict] = None):
- """Initialize the RouterData object.
-
- Args:
- router_data: the router_data dict.
- """
- super().__init__()
- self.session = SessionData(router_data)
- self.headers = HeaderData(router_data)
- self.page = PageData(router_data)
+# Errors caught during pickling of state
+HANDLED_PICKLE_ERRORS = (
+ pickle.PicklingError,
+ AttributeError,
+ IndexError,
+ TypeError,
+ ValueError,
+)
def _no_chain_background_task(
@@ -195,19 +153,9 @@ def _no_chain_background_task(
raise TypeError(f"{fn} is marked as a background task, but is not async.")
-RESERVED_BACKEND_VAR_NAMES = {
- "_backend_vars",
- "_computed_var_dependencies",
- "_substate_var_dependencies",
- "_always_dirty_computed_vars",
- "_always_dirty_substates",
- "_was_touched",
-}
-
-
def _substate_key(
token: str,
- state_cls_or_name: BaseState | Type[BaseState] | str | list[str],
+ state_cls_or_name: BaseState | Type[BaseState] | str | Sequence[str],
) -> str:
"""Get the substate key.
@@ -240,10 +188,11 @@ def _split_substate_key(substate_key: str) -> tuple[str, str]:
return token, state_name
+@dataclasses.dataclass(frozen=True, init=False)
class EventHandlerSetVar(EventHandler):
"""A special event handler to wrap setvar functionality."""
- state_cls: Type[BaseState]
+ state_cls: Type[BaseState] = dataclasses.field(init=False)
def __init__(self, state_cls: Type[BaseState]):
"""Initialize the EventHandlerSetVar.
@@ -254,8 +203,8 @@ class EventHandlerSetVar(EventHandler):
super().__init__(
fn=type(self).setvar,
state_full_name=state_cls.get_full_name(),
- state_cls=state_cls, # type: ignore
)
+ object.__setattr__(self, "state_cls", state_cls)
def setvar(self, var_name: str, value: Any):
"""Set the state variable to the value of the event.
@@ -280,6 +229,7 @@ class EventHandlerSetVar(EventHandler):
Raises:
AttributeError: If the given Var name does not exist on the state.
EventHandlerValueError: If the given Var name is not a str
+ NotImplementedError: If the setter for the given Var is async
"""
from reflex.utils.exceptions import EventHandlerValueError
@@ -288,14 +238,50 @@ class EventHandlerSetVar(EventHandler):
raise EventHandlerValueError(
f"Var name must be passed as a string, got {args[0]!r}"
)
+
+ handler = getattr(self.state_cls, constants.SETTER_PREFIX + args[0], None)
+
# Check that the requested Var setter exists on the State at compile time.
- if getattr(self.state_cls, constants.SETTER_PREFIX + args[0], None) is None:
+ if handler is None:
raise AttributeError(
f"Variable `{args[0]}` cannot be set on `{self.state_cls.get_full_name()}`"
)
+
+ if asyncio.iscoroutinefunction(handler.fn):
+ raise NotImplementedError(
+ f"Setter for {args[0]} is async, which is not supported."
+ )
+
return super().__call__(*args)
+if TYPE_CHECKING:
+ from pydantic.v1.fields import ModelField
+
+
+def get_var_for_field(cls: Type[BaseState], f: ModelField):
+ """Get a Var instance for a Pydantic field.
+
+ Args:
+ cls: The state class.
+ f: The Pydantic field.
+
+ Returns:
+ The Var instance.
+ """
+ from reflex.vars import Field
+
+ field_name = format.format_state_name(cls.get_full_name()) + "." + f.name
+
+ return dispatch(
+ field_name=field_name,
+ var_data=VarData.from_state(cls, f.name),
+ result_var_type=f.outer_type_
+ if get_origin(f.outer_type_) is not Field
+ else get_args(f.outer_type_)[0],
+ )
+
+
class BaseState(Base, ABC, extra=pydantic.Extra.allow):
"""The state of the app."""
@@ -303,7 +289,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
vars: ClassVar[Dict[str, Var]] = {}
# The base vars of the class.
- base_vars: ClassVar[Dict[str, BaseVar]] = {}
+ base_vars: ClassVar[Dict[str, Var]] = {}
# The computed vars of the class.
computed_vars: ClassVar[Dict[str, ComputedVar]] = {}
@@ -311,10 +297,10 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
# Vars inherited by the parent state.
inherited_vars: ClassVar[Dict[str, Var]] = {}
- # Backend vars that are never sent to the client.
+ # Backend base vars that are never sent to the client.
backend_vars: ClassVar[Dict[str, Any]] = {}
- # Backend vars inherited
+ # Backend base vars inherited
inherited_backend_vars: ClassVar[Dict[str, Any]] = {}
# The event handlers.
@@ -350,7 +336,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
# The routing path that triggered the state
router_data: Dict[str, Any] = {}
- # Per-instance copy of backend variable values
+ # Per-instance copy of backend base variable values
_backend_vars: Dict[str, Any] = {}
# The router data for the current page
@@ -359,6 +345,9 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
# Whether the state has ever been touched since instantiation.
_was_touched: bool = False
+ # Whether this state class is a mixin and should not be instantiated.
+ _mixin: ClassVar[bool] = False
+
# A special event handler for setting base vars.
setvar: ClassVar[EventHandler]
@@ -404,11 +393,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
# Create a fresh copy of the backend variables for this instance
self._backend_vars = copy.deepcopy(
- {
- name: item
- for name, item in self.backend_vars.items()
- if name not in self.computed_vars
- }
+ {name: item for name, item in self.backend_vars.items()}
)
def __repr__(self) -> str:
@@ -428,17 +413,32 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
"""
return [
v
- for mixin in cls.__mro__
- if mixin is cls or not issubclass(mixin, (BaseState, ABC))
- for v in mixin.__dict__.values()
- if isinstance(v, ComputedVar)
+ for mixin in cls._mixins() + [cls]
+ for name, v in mixin.__dict__.items()
+ if is_computed_var(v) and name not in cls.inherited_vars
]
@classmethod
- def __init_subclass__(cls, **kwargs):
+ def _validate_module_name(cls) -> None:
+ """Check if the module name is valid.
+
+ Reflex uses ___ as state name module separator.
+
+ Raises:
+ NameError: If the module name is invalid.
+ """
+ if "___" in cls.__module__:
+ raise NameError(
+ "The module name of a State class cannot contain '___'. "
+ "Please rename the module."
+ )
+
+ @classmethod
+ def __init_subclass__(cls, mixin: bool = False, **kwargs):
"""Do some magic for the subclass initialization.
Args:
+ mixin: Whether the subclass is a mixin and should not be initialized.
**kwargs: The kwargs to pass to the pydantic init_subclass method.
Raises:
@@ -447,10 +447,23 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
from reflex.utils.exceptions import StateValueError
super().__init_subclass__(**kwargs)
+
+ cls._mixin = mixin
+ if mixin:
+ return
+
+ # Handle locally-defined states for pickling.
+ if "" in cls.__qualname__:
+ cls._handle_local_def()
+
+ # Validate the module name.
+ cls._validate_module_name()
+
# Event handlers should not shadow builtin state methods.
cls._check_overridden_methods()
+
# Computed vars should not shadow builtin state props.
- cls._check_overriden_basevars()
+ cls._check_overridden_basevars()
# Reset subclass tracking for this class.
cls.class_subclasses = set()
@@ -465,61 +478,51 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
cls.inherited_backend_vars = parent_state.backend_vars
# Check if another substate class with the same name has already been defined.
- if cls.__name__ in set(c.__name__ for c in parent_state.class_subclasses):
- if is_testing_env():
- # Clear existing subclass with same name when app is reloaded via
- # utils.prerequisites.get_app(reload=True)
- parent_state.class_subclasses = set(
- c
- for c in parent_state.class_subclasses
- if c.__name__ != cls.__name__
- )
- else:
- # During normal operation, subclasses cannot have the same name, even if they are
- # defined in different modules.
- raise StateValueError(
- f"The substate class '{cls.__name__}' has been defined multiple times. "
- "Shadowing substate classes is not allowed."
- )
+ if cls.get_name() in set(
+ c.get_name() for c in parent_state.class_subclasses
+ ):
+ # This should not happen, since we have added module prefix to state names in #3214
+ raise StateValueError(
+ f"The substate class '{cls.get_name()}' has been defined multiple times. "
+ "Shadowing substate classes is not allowed."
+ )
# Track this new subclass in the parent state's subclasses set.
parent_state.class_subclasses.add(cls)
# Get computed vars.
computed_vars = cls._get_computed_vars()
+ cls._check_overridden_computed_vars()
new_backend_vars = {
name: value
for name, value in cls.__dict__.items()
- if types.is_backend_variable(name, cls)
- and name not in RESERVED_BACKEND_VAR_NAMES
- and name not in cls.inherited_backend_vars
- and not isinstance(value, FunctionType)
- and not isinstance(value, ComputedVar)
- }
-
- # Get backend computed vars
- backend_computed_vars = {
- v._var_name: v._var_set_state(cls)
- for v in computed_vars
- if types.is_backend_variable(v._var_name, cls)
- and v._var_name not in cls.inherited_backend_vars
+ if types.is_backend_base_variable(name, cls)
}
+ # Add annotated backend vars that may not have a default value.
+ new_backend_vars.update(
+ {
+ name: cls._get_var_default(name, annotation_value)
+ for name, annotation_value in cls._get_type_hints().items()
+ if name not in new_backend_vars
+ and types.is_backend_base_variable(name, cls)
+ }
+ )
cls.backend_vars = {
**cls.inherited_backend_vars,
**new_backend_vars,
- **backend_computed_vars,
}
# Set the base and computed vars.
cls.base_vars = {
- f.name: BaseVar(_var_name=f.name, _var_type=f.outer_type_)._var_set_state(
- cls
- )
+ f.name: get_var_for_field(cls, f)
for f in cls.get_fields().values()
if f.name not in cls.get_skip_vars()
}
- cls.computed_vars = {v._var_name: v._var_set_state(cls) for v in computed_vars}
+ cls.computed_vars = {
+ v._js_expr: v._replace(merge_var_data=VarData.from_state(cls))
+ for v in computed_vars
+ }
cls.vars = {
**cls.inherited_vars,
**cls.base_vars,
@@ -540,13 +543,18 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
for mixin in cls._mixins():
for name, value in mixin.__dict__.items():
- if isinstance(value, ComputedVar):
+ if name in cls.inherited_vars:
+ continue
+ if is_computed_var(value):
fget = cls._copy_fn(value.fget)
- newcv = ComputedVar(fget=fget, _var_name=value._var_name)
- newcv._var_set_state(cls)
+ newcv = value._replace(fget=fget, _var_data=VarData.from_state(cls))
+ # cleanup refs to mixin cls in var_data
setattr(cls, name, newcv)
- cls.computed_vars[newcv._var_name] = newcv
- cls.vars[newcv._var_name] = newcv
+ cls.computed_vars[newcv._js_expr] = newcv
+ cls.vars[newcv._js_expr] = newcv
+ continue
+ if types.is_backend_base_variable(name, mixin):
+ cls.backend_vars[name] = copy.deepcopy(value)
continue
if events.get(name) is not None:
continue
@@ -566,6 +574,9 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
cls.event_handlers[name] = handler
setattr(cls, name, handler)
+ # Initialize per-class var dependency tracking.
+ cls._computed_var_dependencies = defaultdict(set)
+ cls._substate_var_dependencies = defaultdict(set)
cls._init_var_dependency_dicts()
@staticmethod
@@ -608,6 +619,48 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
and hasattr(value, "__code__")
)
+ @classmethod
+ def _evaluate(
+ cls, f: Callable[[Self], Any], of_type: Union[type, None] = None
+ ) -> Var:
+ """Evaluate a function to a ComputedVar. Experimental.
+
+ Args:
+ f: The function to evaluate.
+ of_type: The type of the ComputedVar. Defaults to Component.
+
+ Returns:
+ The ComputedVar.
+ """
+ console.warn(
+ "The _evaluate method is experimental and may be removed in future versions."
+ )
+ from reflex.components.component import Component
+
+ of_type = of_type or Component
+
+ unique_var_name = get_unique_variable_name()
+
+ @computed_var(_js_expr=unique_var_name, return_type=of_type)
+ def computed_var_func(state: Self):
+ result = f(state)
+
+ if not _isinstance(result, of_type):
+ console.warn(
+ f"Inline ComputedVar {f} expected type {of_type}, got {type(result)}. "
+ "You can specify expected type with `of_type` argument."
+ )
+
+ return result
+
+ setattr(cls, unique_var_name, computed_var_func)
+ cls.computed_vars[unique_var_name] = computed_var_func
+ cls.vars[unique_var_name] = computed_var_func
+ cls._update_substate_inherited_vars({unique_var_name: computed_var_func})
+ cls._always_dirty_computed_vars.add(unique_var_name)
+
+ return getattr(cls, unique_var_name)
+
@classmethod
def _mixins(cls) -> List[Type]:
"""Get the mixin classes of the state.
@@ -618,10 +671,46 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
return [
mixin
for mixin in cls.__mro__
- if not issubclass(mixin, (BaseState, ABC))
- and mixin not in [pydantic.BaseModel, Base]
+ if (
+ mixin not in [pydantic.BaseModel, Base, cls]
+ and issubclass(mixin, BaseState)
+ and mixin._mixin is True
+ )
]
+ @classmethod
+ def _handle_local_def(cls):
+ """Handle locally-defined states for pickling."""
+ known_names = dir(reflex.istate.dynamic)
+ proposed_name = cls.__name__
+ for ix in range(len(known_names)):
+ if proposed_name not in known_names:
+ break
+ proposed_name = f"{cls.__name__}_{ix}"
+ setattr(reflex.istate.dynamic, proposed_name, cls)
+ cls.__original_name__ = cls.__name__
+ cls.__original_module__ = cls.__module__
+ cls.__name__ = cls.__qualname__ = proposed_name
+ cls.__module__ = reflex.istate.dynamic.__name__
+
+ @classmethod
+ def _get_type_hints(cls) -> dict[str, Any]:
+ """Get the type hints for this class.
+
+ If the class is dynamic, evaluate the type hints with the original
+ module in the local namespace.
+
+ Returns:
+ The type hints dict.
+ """
+ original_module = getattr(cls, "__original_module__", None)
+ if original_module is not None:
+ localns = sys.modules[original_module].__dict__
+ else:
+ localns = None
+
+ return get_type_hints(cls, localns=localns)
+
@classmethod
def _init_var_dependency_dicts(cls):
"""Initialize the var dependency tracking dicts.
@@ -632,10 +721,6 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
Additional updates tracking dicts for vars and substates that always
need to be recomputed.
"""
- # Initialize per-class var dependency tracking.
- cls._computed_var_dependencies = defaultdict(set)
- cls._substate_var_dependencies = defaultdict(set)
-
inherited_vars = set(cls.inherited_vars).union(
set(cls.inherited_backend_vars),
)
@@ -676,12 +761,15 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
parent_state.get_parent_state(),
)
+ # Reset cached schema value
+ cls._to_schema.cache_clear()
+
@classmethod
def _check_overridden_methods(cls):
"""Check for shadow methods and raise error if any.
Raises:
- NameError: When an event handler shadows an inbuilt state method.
+ EventHandlerShadowsBuiltInStateMethod: When an event handler shadows an inbuilt state method.
"""
overridden_methods = set()
state_base_functions = cls._get_base_functions()
@@ -695,21 +783,37 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
overridden_methods.add(method.__name__)
for method_name in overridden_methods:
- raise NameError(
+ raise EventHandlerShadowsBuiltInStateMethod(
f"The event handler name `{method_name}` shadows a builtin State method; use a different name instead"
)
@classmethod
- def _check_overriden_basevars(cls):
+ def _check_overridden_basevars(cls):
"""Check for shadow base vars and raise error if any.
Raises:
- NameError: When a computed var shadows a base var.
+ ComputedVarShadowsBaseVars: When a computed var shadows a base var.
"""
for computed_var_ in cls._get_computed_vars():
- if computed_var_._var_name in cls.__annotations__:
- raise NameError(
- f"The computed var name `{computed_var_._var_name}` shadows a base var in {cls.__module__}.{cls.__name__}; use a different name instead"
+ if computed_var_._js_expr in cls.__annotations__:
+ raise ComputedVarShadowsBaseVars(
+ f"The computed var name `{computed_var_._js_expr}` shadows a base var in {cls.__module__}.{cls.__name__}; use a different name instead"
+ )
+
+ @classmethod
+ def _check_overridden_computed_vars(cls) -> None:
+ """Check for shadow computed vars and raise error if any.
+
+ Raises:
+ ComputedVarShadowsStateVar: When a computed var shadows another.
+ """
+ for name, cv in cls.__dict__.items():
+ if not is_computed_var(cv):
+ continue
+ name = cv._js_expr
+ if name in cls.inherited_vars or name in cls.inherited_backend_vars:
+ raise ComputedVarShadowsStateVar(
+ f"The computed var name `{cv._js_expr}` shadows a var in {cls.__module__}.{cls.__name__}; use a different name instead"
)
@classmethod
@@ -728,7 +832,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
"dirty_substates",
"router_data",
}
- | RESERVED_BACKEND_VAR_NAMES
+ | types.RESERVED_BACKEND_VAR_NAMES
)
@classmethod
@@ -736,15 +840,19 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
def get_parent_state(cls) -> Type[BaseState] | None:
"""Get the parent state.
+ Raises:
+ ValueError: If more than one parent state is found.
+
Returns:
The parent state.
"""
parent_states = [
base
for base in cls.__bases__
- if types._issubclass(base, BaseState) and base is not BaseState
+ if issubclass(base, BaseState) and base is not BaseState and not base._mixin
]
- assert len(parent_states) < 2, "Only one parent state is allowed."
+ if len(parent_states) >= 2:
+ raise ValueError(f"Only one parent state is allowed {parent_states}.")
return parent_states[0] if len(parent_states) == 1 else None # type: ignore
@classmethod
@@ -764,7 +872,8 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
Returns:
The name of the state.
"""
- return format.to_snake_case(cls.__name__)
+ module = cls.__module__.replace(".", "___")
+ return format.to_snake_case(f"{module}___{cls.__name__}")
@classmethod
@functools.lru_cache()
@@ -828,7 +937,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
return getattr(substate, name)
@classmethod
- def _init_var(cls, prop: BaseVar):
+ def _init_var(cls, prop: Var):
"""Initialize a variable.
Args:
@@ -844,7 +953,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
"State vars must be primitive Python types, "
"Plotly figures, Pandas dataframes, "
"or subclasses of rx.Base. "
- f'Found var "{prop._var_name}" with type {prop._var_type}.'
+ f'Found var "{prop._js_expr}" with type {prop._var_type}.'
)
cls._set_var(prop)
cls._create_setter(prop)
@@ -871,8 +980,11 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
)
# create the variable based on name and type
- var = BaseVar(_var_name=name, _var_type=type_)
- var._var_set_state(cls)
+ var = Var(
+ _js_expr=format.format_state_name(cls.get_full_name()) + "." + name,
+ _var_type=type_,
+ _var_data=VarData.from_state(cls, name),
+ ).guess_type()
# add the pydantic field dynamically (must be done before _init_var)
cls.add_field(var, default_value)
@@ -891,13 +1003,13 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
cls._init_var_dependency_dicts()
@classmethod
- def _set_var(cls, prop: BaseVar):
+ def _set_var(cls, prop: Var):
"""Set the var as a class member.
Args:
prop: The var instance to set.
"""
- setattr(cls, prop._var_name, prop)
+ setattr(cls, prop._var_field_name, prop)
@classmethod
def _create_event_handler(cls, fn):
@@ -917,7 +1029,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
cls.setvar = cls.event_handlers["setvar"] = EventHandlerSetVar(state_cls=cls)
@classmethod
- def _create_setter(cls, prop: BaseVar):
+ def _create_setter(cls, prop: Var):
"""Create a setter for the var.
Args:
@@ -930,14 +1042,14 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
setattr(cls, setter_name, event_handler)
@classmethod
- def _set_default_value(cls, prop: BaseVar):
+ def _set_default_value(cls, prop: Var):
"""Set the default value for the var.
Args:
prop: The var to set the default value for.
"""
# Get the pydantic field for the var.
- field = cls.get_fields()[prop._var_name]
+ field = cls.get_fields()[prop._var_field_name]
if field.required:
default_value = prop.get_default_value()
if default_value is not None:
@@ -949,7 +1061,27 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
and not types.is_optional(prop._var_type)
):
# Ensure frontend uses null coalescing when accessing.
- prop._var_type = Optional[prop._var_type]
+ object.__setattr__(prop, "_var_type", Optional[prop._var_type])
+
+ @classmethod
+ def _get_var_default(cls, name: str, annotation_value: Any) -> Any:
+ """Get the default value of a (backend) var.
+
+ Args:
+ name: The name of the var.
+ annotation_value: The annotation value of the var.
+
+ Returns:
+ The default value of the var or None.
+ """
+ try:
+ return getattr(cls, name)
+ except AttributeError:
+ try:
+ return Var("", _var_type=annotation_value).get_default_value()
+ except TypeError:
+ pass
+ return None
@staticmethod
def _get_base_functions() -> dict[str, FunctionType]:
@@ -964,6 +1096,27 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
if not func[0].startswith("__")
}
+ @classmethod
+ def _update_substate_inherited_vars(cls, vars_to_add: dict[str, Var]):
+ """Update the inherited vars of substates recursively when new vars are added.
+
+ Also updates the var dependency tracking dicts after adding vars.
+
+ Args:
+ vars_to_add: names to Var instances to add to substates
+ """
+ for substate_class in cls.class_subclasses:
+ for name, var in vars_to_add.items():
+ if types.is_backend_base_variable(name, cls):
+ substate_class.backend_vars.setdefault(name, var)
+ substate_class.inherited_backend_vars.setdefault(name, var)
+ else:
+ substate_class.vars.setdefault(name, var)
+ substate_class.inherited_vars.setdefault(name, var)
+ substate_class._update_substate_inherited_vars(vars_to_add)
+ # Reinitialize dependency tracking dicts.
+ cls._init_var_dependency_dicts()
+
@classmethod
def setup_dynamic_args(cls, args: dict[str, str]):
"""Set up args for easy access in renderer.
@@ -971,21 +1124,24 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
Args:
args: a dict of args
"""
+ if not args:
+ return
+
+ cls._check_overwritten_dynamic_args(list(args.keys()))
def argsingle_factory(param):
- @ComputedVar
def inner_func(self) -> str:
return self.router.page.params.get(param, "")
return inner_func
def arglist_factory(param):
- @ComputedVar
- def inner_func(self) -> List:
+ def inner_func(self) -> List[str]:
return self.router.page.params.get(param, [])
return inner_func
+ dynamic_vars = {}
for param, value in args.items():
if value == constants.RouteArgType.SINGLE:
func = argsingle_factory(param)
@@ -993,13 +1149,39 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
func = arglist_factory(param)
else:
continue
- # to allow passing as a prop
- func._var_name = param
- cls.vars[param] = cls.computed_vars[param] = func._var_set_state(cls) # type: ignore
- setattr(cls, param, func)
+ dynamic_vars[param] = DynamicRouteVar(
+ fget=func,
+ cache=True,
+ _js_expr=param,
+ _var_data=VarData.from_state(cls),
+ )
+ setattr(cls, param, dynamic_vars[param])
- # Reinitialize dependency tracking dicts.
- cls._init_var_dependency_dicts()
+ # Update tracking dicts.
+ cls.computed_vars.update(dynamic_vars)
+ cls.vars.update(dynamic_vars)
+ cls._update_substate_inherited_vars(dynamic_vars)
+
+ @classmethod
+ def _check_overwritten_dynamic_args(cls, args: list[str]):
+ """Check if dynamic args are shadowing existing vars. Recursively checks all child states.
+
+ Args:
+ args: a dict of args
+
+ Raises:
+ DynamicRouteArgShadowsStateVar: If a dynamic arg is shadowing an existing var.
+ """
+ for arg in args:
+ if (
+ arg in cls.computed_vars
+ and not isinstance(cls.computed_vars[arg], DynamicRouteVar)
+ ) or arg in cls.base_vars:
+ raise DynamicRouteArgShadowsStateVar(
+ f"Dynamic route arg '{arg}' is shadowing an existing var in {cls.__module__}.{cls.__name__}"
+ )
+ for substate in cls.get_substates():
+ substate._check_overwritten_dynamic_args(args)
def __getattribute__(self, name: str) -> Any:
"""Get the state var.
@@ -1068,6 +1250,9 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
Args:
name: The name of the attribute.
value: The value of the attribute.
+
+ Raises:
+ SetUndefinedStateVarError: If a value of a var is set without first defining it.
"""
if isinstance(value, MutableProxy):
# unwrap proxy objects when assigning back to the state
@@ -1079,15 +1264,38 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
setattr(self.parent_state, name, value)
return
- if (
- types.is_backend_variable(name, self.__class__)
- and name not in RESERVED_BACKEND_VAR_NAMES
- ):
+ if name in self.backend_vars:
self._backend_vars.__setitem__(name, value)
self.dirty_vars.add(name)
self._mark_dirty()
return
+ if (
+ name not in self.vars
+ and name not in self.get_skip_vars()
+ and not name.startswith("__")
+ and not name.startswith(
+ f"_{getattr(type(self), '__original_name__', type(self).__name__)}__"
+ )
+ ):
+ raise SetUndefinedStateVarError(
+ f"The state variable '{name}' has not been defined in '{type(self).__name__}'. "
+ f"All state variables must be declared before they can be set."
+ )
+
+ fields = self.get_fields()
+
+ if name in fields and not _isinstance(
+ value, (field_type := fields[name].outer_type_)
+ ):
+ console.deprecate(
+ "mismatched-type-assignment",
+ f"Tried to assign value {value} of type {type(value)} to field {type(self).__name__}.{name} of type {field_type}."
+ " This might lead to unexpected behavior.",
+ "0.6.5",
+ "0.7.0",
+ )
+
# Set the attribute.
super().__setattr__(name, value)
@@ -1115,6 +1323,10 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
default = copy.deepcopy(field.default)
setattr(self, prop_name, default)
+ # Reset the backend vars.
+ for prop_name, value in self.backend_vars.items():
+ setattr(self, prop_name, copy.deepcopy(value))
+
# Recursively reset the substates.
for substate in self.substates.values():
substate.reset()
@@ -1217,6 +1429,17 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
parent_states_with_name.append((parent_state.get_full_name(), parent_state))
return parent_states_with_name
+ def _get_root_state(self) -> BaseState:
+ """Get the root state of the state tree.
+
+ Returns:
+ The root state of the state tree.
+ """
+ parent_state = self
+ while parent_state.parent_state is not None:
+ parent_state = parent_state.parent_state
+ return parent_state
+
async def _populate_parent_states(self, target_state_cls: Type[BaseState]):
"""Populate substates in the tree between the target_state_cls and common ancestor of this state.
@@ -1276,10 +1499,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
Returns:
The instance of state_cls associated with this state's client_token.
"""
- if self.parent_state is None:
- root_state = self
- else:
- root_state = self._get_parent_states()[-1][1]
+ root_state = self._get_root_state()
return root_state.get_substate(state_cls.get_full_name().split("."))
async def _get_state_from_redis(self, state_cls: Type[BaseState]) -> BaseState:
@@ -1430,24 +1650,46 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
The valid StateUpdate containing the events and final flag.
"""
# get the delta from the root of the state tree
- state = self
- while state.parent_state is not None:
- state = state.parent_state
+ state = self._get_root_state()
token = self.router.session.client_token
# Convert valid EventHandler and EventSpec into Event
fixed_events = fix_events(self._check_valid(handler, events), token)
- # Get the delta after processing the event.
- delta = state.get_delta()
- state._clean()
+ try:
+ # Get the delta after processing the event.
+ delta = state.get_delta()
+ state._clean()
- return StateUpdate(
- delta=delta,
- events=fixed_events,
- final=final if not handler.is_background else True,
- )
+ return StateUpdate(
+ delta=delta,
+ events=fixed_events,
+ final=final if not handler.is_background else True,
+ )
+ except Exception as ex:
+ state._clean()
+
+ app_instance = getattr(prerequisites.get_app(), constants.CompileVars.APP)
+
+ event_specs = app_instance.backend_exception_handler(ex)
+
+ if event_specs is None:
+ return StateUpdate()
+
+ event_specs_correct_type = cast(
+ Union[List[Union[EventSpec, EventHandler]], None],
+ [event_specs] if isinstance(event_specs, EventSpec) else event_specs,
+ )
+ fixed_events = fix_events(
+ event_specs_correct_type,
+ token,
+ router_data=state.router_data,
+ )
+ return StateUpdate(
+ events=fixed_events,
+ final=True,
+ )
async def _process_event(
self, handler: EventHandler, state: BaseState | StateProxy, payload: Dict
@@ -1463,7 +1705,6 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
StateUpdate object
"""
from reflex.utils import telemetry
- from reflex.utils.exceptions import ReflexError
# Get the function to process the event.
fn = functools.partial(handler.fn, state)
@@ -1501,13 +1742,15 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
# If an error occurs, throw a window alert.
except Exception as ex:
- error = traceback.format_exc()
- print(error)
- if isinstance(ex, ReflexError):
- telemetry.send("error", context="backend", detail=str(ex))
+ telemetry.send_error(ex, context="backend")
+
+ app_instance = getattr(prerequisites.get_app(), constants.CompileVars.APP)
+
+ event_specs = app_instance.backend_exception_handler(ex)
+
yield state._as_state_update(
handler,
- window_alert("An error occurred. See logs for details."),
+ event_specs,
final=True,
)
@@ -1523,11 +1766,26 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
if actual_var is not None:
actual_var.mark_dirty(instance=self)
- def _dirty_computed_vars(self, from_vars: set[str] | None = None) -> set[str]:
+ def _expired_computed_vars(self) -> set[str]:
+ """Determine ComputedVars that need to be recalculated based on the expiration time.
+
+ Returns:
+ Set of computed vars to include in the delta.
+ """
+ return set(
+ cvar
+ for cvar in self.computed_vars
+ if self.computed_vars[cvar].needs_update(instance=self)
+ )
+
+ def _dirty_computed_vars(
+ self, from_vars: set[str] | None = None, include_backend: bool = True
+ ) -> set[str]:
"""Determine ComputedVars that need to be recalculated based on the given vars.
Args:
from_vars: find ComputedVar that depend on this set of vars. If unspecified, will use the dirty_vars.
+ include_backend: whether to include backend vars in the calculation.
Returns:
Set of computed vars to include in the delta.
@@ -1536,6 +1794,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
cvar
for dirty_var in from_vars or self.dirty_vars
for cvar in self._computed_var_dependencies[dirty_var]
+ if include_backend or not self.computed_vars[cvar]._backend
)
@classmethod
@@ -1571,19 +1830,25 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
self.dirty_vars.update(self._always_dirty_computed_vars)
self._mark_dirty()
+ frontend_computed_vars: set[str] = {
+ name for name, cv in self.computed_vars.items() if not cv._backend
+ }
+
# Return the dirty vars for this instance, any cached/dependent computed vars,
# and always dirty computed vars (cache=False)
delta_vars = (
self.dirty_vars.intersection(self.base_vars)
- .union(self._dirty_computed_vars())
+ .union(self.dirty_vars.intersection(frontend_computed_vars))
+ .union(self._dirty_computed_vars(include_backend=False))
.union(self._always_dirty_computed_vars)
)
- subdelta = {
- prop: getattr(self, prop)
+ subdelta: Dict[str, Any] = {
+ prop: self.get_value(getattr(self, prop))
for prop in delta_vars
- if not types.is_backend_variable(prop, self.__class__)
+ if not types.is_backend_base_variable(prop, type(self))
}
+
if len(subdelta) > 0:
delta[self.get_full_name()] = subdelta
@@ -1592,9 +1857,6 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
for substate in self.dirty_substates.union(self._always_dirty_substates):
delta.update(substates[substate].get_delta())
- # Format the delta.
- delta = format.format_state(delta)
-
# Return the delta.
return delta
@@ -1608,6 +1870,9 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
self.parent_state.dirty_substates.add(self.get_name())
self.parent_state._mark_dirty()
+ # Append expired computed vars to dirty_vars to trigger recalculation
+ self.dirty_vars.update(self._expired_computed_vars())
+
# have to mark computed vars dirty to allow access to newly computed
# values within the same ComputedVar function
self._mark_dirty_computed_vars()
@@ -1698,22 +1963,24 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
prop_name: self.get_value(getattr(self, prop_name))
for prop_name in self.base_vars
}
- if initial:
+ if initial and include_computed:
computed_vars = {
# Include initial computed vars.
prop_name: (
cv._initial_value
- if isinstance(cv, ComputedVar)
+ if is_computed_var(cv)
and not isinstance(cv._initial_value, types.Unset)
else self.get_value(getattr(self, prop_name))
)
for prop_name, cv in self.computed_vars.items()
+ if not cv._backend
}
elif include_computed:
computed_vars = {
# Include the computed vars.
prop_name: self.get_value(getattr(self, prop_name))
- for prop_name in self.computed_vars
+ for prop_name, cv in self.computed_vars.items()
+ if not cv._backend
}
else:
computed_vars = {}
@@ -1726,6 +1993,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
for v in self.substates.values()
]:
d.update(substate_d)
+
return d
async def __aenter__(self) -> BaseState:
@@ -1755,7 +2023,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
def __getstate__(self):
"""Get the state for redis serialization.
- This method is called by cloudpickle to serialize the object.
+ This method is called by pickle to serialize the object.
It explicitly removes parent_state and substates because those are serialized separately
by the StateManagerRedis to allow for better horizontal scaling as state size increases.
@@ -1764,15 +2032,106 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
The state dict for serialization.
"""
state = super().__getstate__()
- # Never serialize parent_state or substates
state["__dict__"] = state["__dict__"].copy()
+ if state["__dict__"].get("parent_state") is not None:
+ # Do not serialize router data in substates (only the root state).
+ state["__dict__"].pop("router", None)
+ state["__dict__"].pop("router_data", None)
+ # Never serialize parent_state or substates.
state["__dict__"]["parent_state"] = None
state["__dict__"]["substates"] = {}
state["__dict__"].pop("_was_touched", None)
+ # Remove all inherited vars.
+ for inherited_var_name in self.inherited_vars:
+ state["__dict__"].pop(inherited_var_name, None)
return state
+ @classmethod
+ @functools.lru_cache()
+ def _to_schema(cls) -> str:
+ """Convert a state to a schema.
-EventHandlerSetVar.update_forward_refs()
+ Returns:
+ The hash of the schema.
+ """
+
+ def _field_tuple(
+ field_name: str,
+ ) -> Tuple[str, str, Any, Union[bool, None], Any]:
+ model_field = cls.__fields__[field_name]
+ return (
+ field_name,
+ model_field.name,
+ _serialize_type(model_field.type_),
+ (
+ model_field.required
+ if isinstance(model_field.required, bool)
+ else None
+ ),
+ (model_field.default if is_serializable(model_field.default) else None),
+ )
+
+ return md5(
+ pickle.dumps(
+ list(sorted(_field_tuple(field_name) for field_name in cls.base_vars))
+ )
+ ).hexdigest()
+
+ def _serialize(self) -> bytes:
+ """Serialize the state for redis.
+
+ Returns:
+ The serialized state.
+ """
+ try:
+ return pickle.dumps((self._to_schema(), self))
+ except HANDLED_PICKLE_ERRORS as og_pickle_error:
+ error = (
+ f"Failed to serialize state {self.get_full_name()} due to unpicklable object. "
+ "This state will not be persisted. "
+ )
+ try:
+ import dill
+
+ return dill.dumps((self._to_schema(), self))
+ except ImportError:
+ error += (
+ f"Pickle error: {og_pickle_error}. "
+ "Consider `pip install 'dill>=0.3.8'` for more exotic serialization support."
+ )
+ except HANDLED_PICKLE_ERRORS as ex:
+ error += f"Dill was also unable to pickle the state: {ex}"
+ console.warn(error)
+ return b""
+
+ @classmethod
+ def _deserialize(
+ cls, data: bytes | None = None, fp: BinaryIO | None = None
+ ) -> BaseState:
+ """Deserialize the state from redis/disk.
+
+ data and fp are mutually exclusive, but one must be provided.
+
+ Args:
+ data: The serialized state data.
+ fp: The file pointer to the serialized state data.
+
+ Returns:
+ The deserialized state.
+
+ Raises:
+ ValueError: If both data and fp are provided, or neither are provided.
+ StateSchemaMismatchError: If the state schema does not match the expected schema.
+ """
+ if data is not None and fp is None:
+ (substate_schema, state) = pickle.loads(data)
+ elif fp is not None and data is None:
+ (substate_schema, state) = pickle.load(fp)
+ else:
+ raise ValueError("Only one of `data` or `fp` must be provided")
+ if substate_schema != state._to_schema():
+ raise StateSchemaMismatchError()
+ return state
class State(BaseState):
@@ -1782,6 +2141,70 @@ class State(BaseState):
is_hydrated: bool = False
+T = TypeVar("T", bound=BaseState)
+
+
+def dynamic(func: Callable[[T], Component]):
+ """Create a dynamically generated components from a state class.
+
+ Args:
+ func: The function to generate the component.
+
+ Returns:
+ The dynamically generated component.
+
+ Raises:
+ DynamicComponentInvalidSignature: If the function does not have exactly one parameter.
+ DynamicComponentInvalidSignature: If the function does not have a type hint for the state class.
+ """
+ number_of_parameters = len(inspect.signature(func).parameters)
+
+ func_signature = get_type_hints(func)
+
+ if "return" in func_signature:
+ func_signature.pop("return")
+
+ values = list(func_signature.values())
+
+ if number_of_parameters != 1:
+ raise DynamicComponentInvalidSignature(
+ "The function must have exactly one parameter, which is the state class."
+ )
+
+ if len(values) != 1:
+ raise DynamicComponentInvalidSignature(
+ "You must provide a type hint for the state class in the function."
+ )
+
+ state_class: Type[T] = values[0]
+
+ def wrapper() -> Component:
+ from reflex.components.base.fragment import fragment
+
+ return fragment(state_class._evaluate(lambda state: func(state)))
+
+ return wrapper
+
+
+class FrontendEventExceptionState(State):
+ """Substate for handling frontend exceptions."""
+
+ @event
+ def handle_frontend_exception(self, stack: str, component_stack: str) -> None:
+ """Handle frontend exceptions.
+
+ If a frontend exception handler is provided, it will be called.
+ Otherwise, the default frontend exception handler will be called.
+
+ Args:
+ stack: The stack trace of the exception.
+ component_stack: The stack trace of the component where the exception occurred.
+
+ """
+ app_instance = getattr(prerequisites.get_app(), constants.CompileVars.APP)
+ app_instance.frontend_exception_handler(Exception(stack))
+
+
class UpdateVarsInternalState(State):
"""Substate for handling internal state var updates."""
@@ -1833,7 +2256,7 @@ class OnLoadInternalState(State):
]
-class ComponentState(Base):
+class ComponentState(State, mixin=True):
"""Base class to allow for the creation of a state instance per component.
This allows for the bundling of UI and state logic into a single class,
@@ -1875,6 +2298,16 @@ class ComponentState(Base):
# The number of components created from this class.
_per_component_state_instance_count: ClassVar[int] = 0
+ @classmethod
+ def __init_subclass__(cls, mixin: bool = True, **kwargs):
+ """Overwrite mixin default to True.
+
+ Args:
+ mixin: Whether the subclass is a mixin and should not be initialized.
+ **kwargs: The kwargs to pass to the pydantic init_subclass method.
+ """
+ super().__init_subclass__(mixin=mixin, **kwargs)
+
@classmethod
def get_component(cls, *children, **props) -> "Component":
"""Get the component instance.
@@ -1903,7 +2336,14 @@ class ComponentState(Base):
"""
cls._per_component_state_instance_count += 1
state_cls_name = f"{cls.__name__}_n{cls._per_component_state_instance_count}"
- component_state = type(state_cls_name, (cls, State), {})
+ component_state = type(
+ state_cls_name,
+ (cls, State),
+ {"__module__": reflex.istate.dynamic.__name__},
+ mixin=False,
+ )
+ # Save a reference to the dynamic state for pickle/unpickle.
+ setattr(reflex.istate.dynamic, state_cls_name, component_state)
component = component_state.get_component(*children, **props)
component.State = component_state
return component
@@ -1928,25 +2368,45 @@ class StateProxy(wrapt.ObjectProxy):
class State(rx.State):
counter: int = 0
- @rx.background
+ @rx.event(background=True)
async def bg_increment(self):
await asyncio.sleep(1)
async with self:
self.counter += 1
"""
- def __init__(self, state_instance):
+ def __init__(
+ self, state_instance, parent_state_proxy: Optional["StateProxy"] = None
+ ):
"""Create a proxy for a state instance.
+ If `get_state` is used on a StateProxy, the resulting state will be
+ linked to the given state via parent_state_proxy. The first state in the
+ chain is the state that initiated the background task.
+
Args:
state_instance: The state instance to proxy.
+ parent_state_proxy: The parent state proxy, for linked mutability and context tracking.
"""
super().__init__(state_instance)
# compile is not relevant to backend logic
self._self_app = getattr(prerequisites.get_app(), constants.CompileVars.APP)
- self._self_substate_path = state_instance.get_full_name().split(".")
+ self._self_substate_path = tuple(state_instance.get_full_name().split("."))
self._self_actx = None
self._self_mutable = False
+ self._self_actx_lock = asyncio.Lock()
+ self._self_actx_lock_holder = None
+ self._self_parent_state_proxy = parent_state_proxy
+
+ def _is_mutable(self) -> bool:
+ """Check if the state is mutable.
+
+ Returns:
+ Whether the state is mutable.
+ """
+ if self._self_parent_state_proxy is not None:
+ return self._self_parent_state_proxy._is_mutable() or self._self_mutable
+ return self._self_mutable
async def __aenter__(self) -> StateProxy:
"""Enter the async context manager protocol.
@@ -1959,7 +2419,31 @@ class StateProxy(wrapt.ObjectProxy):
Returns:
This StateProxy instance in mutable mode.
+
+ Raises:
+ ImmutableStateError: If the state is already mutable.
"""
+ if self._self_parent_state_proxy is not None:
+ parent_state = (
+ await self._self_parent_state_proxy.__aenter__()
+ ).__wrapped__
+ super().__setattr__(
+ "__wrapped__",
+ await parent_state.get_state(
+ State.get_class_substate(self._self_substate_path)
+ ),
+ )
+ return self
+ current_task = asyncio.current_task()
+ if (
+ self._self_actx_lock.locked()
+ and current_task == self._self_actx_lock_holder
+ ):
+ raise ImmutableStateError(
+ "The state is already mutable. Do not nest `async with self` blocks."
+ )
+ await self._self_actx_lock.acquire()
+ self._self_actx_lock_holder = current_task
self._self_actx = self._self_app.modify_state(
token=_substate_key(
self.__wrapped__.router.session.client_token,
@@ -1981,10 +2465,17 @@ class StateProxy(wrapt.ObjectProxy):
Args:
exc_info: The exception info tuple.
"""
+ if self._self_parent_state_proxy is not None:
+ await self._self_parent_state_proxy.__aexit__(*exc_info)
+ return
if self._self_actx is None:
return
self._self_mutable = False
- await self._self_actx.__aexit__(*exc_info)
+ try:
+ await self._self_actx.__aexit__(*exc_info)
+ finally:
+ self._self_actx_lock_holder = None
+ self._self_actx_lock.release()
self._self_actx = None
def __enter__(self):
@@ -2018,7 +2509,7 @@ class StateProxy(wrapt.ObjectProxy):
Raises:
ImmutableStateError: If the state is not in mutable mode.
"""
- if name in ["substates", "parent_state"] and not self._self_mutable:
+ if name in ["substates", "parent_state"] and not self._is_mutable():
raise ImmutableStateError(
"Background task StateProxy is immutable outside of a context "
"manager. Use `async with self` to modify state."
@@ -2058,7 +2549,7 @@ class StateProxy(wrapt.ObjectProxy):
"""
if (
name.startswith("_self_") # wrapper attribute
- or self._self_mutable # lock held
+ or self._is_mutable() # lock held
# non-persisted state attribute
or name in self.__wrapped__.get_skip_vars()
):
@@ -2082,7 +2573,7 @@ class StateProxy(wrapt.ObjectProxy):
Raises:
ImmutableStateError: If the state is not in mutable mode.
"""
- if not self._self_mutable:
+ if not self._is_mutable():
raise ImmutableStateError(
"Background task StateProxy is immutable outside of a context "
"manager. Use `async with self` to modify state."
@@ -2101,12 +2592,14 @@ class StateProxy(wrapt.ObjectProxy):
Raises:
ImmutableStateError: If the state is not in mutable mode.
"""
- if not self._self_mutable:
+ if not self._is_mutable():
raise ImmutableStateError(
"Background task StateProxy is immutable outside of a context "
"manager. Use `async with self` to modify state."
)
- return await self.__wrapped__.get_state(state_cls)
+ return type(self)(
+ await self.__wrapped__.get_state(state_cls), parent_state_proxy=self
+ )
def _as_state_update(self, *args, **kwargs) -> StateUpdate:
"""Temporarily allow mutability to access parent_state.
@@ -2118,25 +2611,37 @@ class StateProxy(wrapt.ObjectProxy):
Returns:
The state update.
"""
+ original_mutable = self._self_mutable
self._self_mutable = True
try:
return self.__wrapped__._as_state_update(*args, **kwargs)
finally:
- self._self_mutable = False
+ self._self_mutable = original_mutable
-class StateUpdate(Base):
+@dataclasses.dataclass(
+ frozen=True,
+)
+class StateUpdate:
"""A state update sent to the frontend."""
# The state delta.
- delta: Delta = {}
+ delta: Delta = dataclasses.field(default_factory=dict)
# Events to be added to the event queue.
- events: List[Event] = []
+ events: List[Event] = dataclasses.field(default_factory=list)
# Whether this is the final state update for the event.
final: bool = True
+ def json(self) -> str:
+ """Convert the state update to a JSON string.
+
+ Returns:
+ The state update as a JSON string.
+ """
+ return format.json_dumps(self)
+
class StateManager(Base, ABC):
"""A class to manage many client states."""
@@ -2151,13 +2656,32 @@ class StateManager(Base, ABC):
Args:
state: The state class to use.
+ Raises:
+ InvalidStateManagerMode: If the state manager mode is invalid.
+
Returns:
- The state manager (either memory or redis).
+ The state manager (either disk, memory or redis).
"""
- redis = prerequisites.get_redis()
- if redis is not None:
- return StateManagerRedis(state=state, redis=redis)
- return StateManagerMemory(state=state)
+ config = get_config()
+ if prerequisites.parse_redis_url() is not None:
+ config.state_manager_mode = constants.StateManagerMode.REDIS
+ if config.state_manager_mode == constants.StateManagerMode.MEMORY:
+ return StateManagerMemory(state=state)
+ if config.state_manager_mode == constants.StateManagerMode.DISK:
+ return StateManagerDisk(state=state)
+ if config.state_manager_mode == constants.StateManagerMode.REDIS:
+ redis = prerequisites.get_redis()
+ if redis is not None:
+ # make sure expiration values are obtained only from the config object on creation
+ return StateManagerRedis(
+ state=state,
+ redis=redis,
+ token_expiration=config.redis_token_expiration,
+ lock_expiration=config.redis_lock_expiration,
+ )
+ raise InvalidStateManagerMode(
+ f"Expected one of: DISK, MEMORY, REDIS, got {config.state_manager_mode}"
+ )
@abstractmethod
async def get_state(self, token: str) -> BaseState:
@@ -2214,6 +2738,7 @@ class StateManagerMemory(StateManager):
"_states_locks": {"exclude": True},
}
+ @override
async def get_state(self, token: str) -> BaseState:
"""Get the state for a token.
@@ -2229,6 +2754,7 @@ class StateManagerMemory(StateManager):
self.states[token] = self.state(_reflex_internal_init=True)
return self.states[token]
+ @override
async def set_state(self, token: str, state: BaseState):
"""Set the state for a token.
@@ -2238,6 +2764,7 @@ class StateManagerMemory(StateManager):
"""
pass
+ @override
@contextlib.asynccontextmanager
async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
"""Modify the state for a token while holding exclusive lock.
@@ -2261,23 +2788,263 @@ class StateManagerMemory(StateManager):
await self.set_state(token, state)
-# Workaround https://github.com/cloudpipe/cloudpickle/issues/408 for dynamic pydantic classes
-if not isinstance(State.validate.__func__, FunctionType):
- cython_function_or_method = type(State.validate.__func__)
+def _default_token_expiration() -> int:
+ """Get the default token expiration time.
- @dill.register(cython_function_or_method)
- def _dill_reduce_cython_function_or_method(pickler, obj):
- # Ignore cython function when pickling.
- pass
+ Returns:
+ The default token expiration time.
+ """
+ return get_config().redis_token_expiration
-@dill.register(type(State))
-def _dill_reduce_state(pickler, obj):
- if obj is not State and issubclass(obj, State):
- # Avoid serializing subclasses of State, instead get them by reference from the State class.
- pickler.save_reduce(State.get_class_substate, (obj.get_full_name(),), obj=obj)
- else:
- dill.Pickler.dispatch[type](pickler, obj)
+def _serialize_type(type_: Any) -> str:
+ """Serialize a type.
+
+ Args:
+ type_: The type to serialize.
+
+ Returns:
+ The serialized type.
+ """
+ if not inspect.isclass(type_):
+ return f"{type_}"
+ return f"{type_.__module__}.{type_.__qualname__}"
+
+
+def is_serializable(value: Any) -> bool:
+ """Check if a value is serializable.
+
+ Args:
+ value: The value to check.
+
+ Returns:
+ Whether the value is serializable.
+ """
+ try:
+ return bool(pickle.dumps(value))
+ except Exception:
+ return False
+
+
+def reset_disk_state_manager():
+ """Reset the disk state manager."""
+ states_directory = prerequisites.get_web_dir() / constants.Dirs.STATES
+ if states_directory.exists():
+ for path in states_directory.iterdir():
+ path.unlink()
+
+
+class StateManagerDisk(StateManager):
+ """A state manager that stores states in memory."""
+
+ # The mapping of client ids to states.
+ states: Dict[str, BaseState] = {}
+
+ # The mutex ensures the dict of mutexes is updated exclusively
+ _state_manager_lock = asyncio.Lock()
+
+ # The dict of mutexes for each client
+ _states_locks: Dict[str, asyncio.Lock] = pydantic.PrivateAttr({})
+
+ # The token expiration time (s).
+ token_expiration: int = pydantic.Field(default_factory=_default_token_expiration)
+
+ class Config:
+ """The Pydantic config."""
+
+ fields = {
+ "_states_locks": {"exclude": True},
+ }
+ keep_untouched = (functools.cached_property,)
+
+ def __init__(self, state: Type[BaseState]):
+ """Create a new state manager.
+
+ Args:
+ state: The state class to use.
+ """
+ super().__init__(state=state)
+
+ path_ops.mkdir(self.states_directory)
+
+ self._purge_expired_states()
+
+ @functools.cached_property
+ def states_directory(self) -> Path:
+ """Get the states directory.
+
+ Returns:
+ The states directory.
+ """
+ return prerequisites.get_web_dir() / constants.Dirs.STATES
+
+ def _purge_expired_states(self):
+ """Purge expired states from the disk."""
+ import time
+
+ for path in path_ops.ls(self.states_directory):
+ # check path is a pickle file
+ if path.suffix != ".pkl":
+ continue
+
+ # load last edited field from file
+ last_edited = path.stat().st_mtime
+
+ # check if the file is older than the token expiration time
+ if time.time() - last_edited > self.token_expiration:
+ # remove the file
+ path.unlink()
+
+ def token_path(self, token: str) -> Path:
+ """Get the path for a token.
+
+ Args:
+ token: The token to get the path for.
+
+ Returns:
+ The path for the token.
+ """
+ return (
+ self.states_directory / f"{md5(token.encode()).hexdigest()}.pkl"
+ ).absolute()
+
+ async def load_state(self, token: str) -> BaseState | None:
+ """Load a state object based on the provided token.
+
+ Args:
+ token: The token used to identify the state object.
+
+ Returns:
+ The loaded state object or None.
+ """
+ token_path = self.token_path(token)
+
+ if token_path.exists():
+ try:
+ with token_path.open(mode="rb") as file:
+ return BaseState._deserialize(fp=file)
+ except Exception:
+ pass
+
+ async def populate_substates(
+ self, client_token: str, state: BaseState, root_state: BaseState
+ ):
+ """Populate the substates of a state object.
+
+ Args:
+ client_token: The client token.
+ state: The state object to populate.
+ root_state: The root state object.
+ """
+ for substate in state.get_substates():
+ substate_token = _substate_key(client_token, substate)
+
+ fresh_instance = await root_state.get_state(substate)
+ instance = await self.load_state(substate_token)
+ if instance is not None:
+ # Ensure all substates exist, even if they weren't serialized previously.
+ instance.substates = fresh_instance.substates
+ else:
+ instance = fresh_instance
+ state.substates[substate.get_name()] = instance
+ instance.parent_state = state
+
+ await self.populate_substates(client_token, instance, root_state)
+
+ @override
+ async def get_state(
+ self,
+ token: str,
+ ) -> BaseState:
+ """Get the state for a token.
+
+ Args:
+ token: The token to get the state for.
+
+ Returns:
+ The state for the token.
+ """
+ client_token = _split_substate_key(token)[0]
+ root_state = self.states.get(client_token)
+ if root_state is not None:
+ # Retrieved state from memory.
+ return root_state
+
+ # Deserialize root state from disk.
+ root_state = await self.load_state(_substate_key(client_token, self.state))
+ # Create a new root state tree with all substates instantiated.
+ fresh_root_state = self.state(_reflex_internal_init=True)
+ if root_state is None:
+ root_state = fresh_root_state
+ else:
+ # Ensure all substates exist, even if they were not serialized previously.
+ root_state.substates = fresh_root_state.substates
+ self.states[client_token] = root_state
+ await self.populate_substates(client_token, root_state, root_state)
+ return root_state
+
+ async def set_state_for_substate(self, client_token: str, substate: BaseState):
+ """Set the state for a substate.
+
+ Args:
+ client_token: The client token.
+ substate: The substate to set.
+ """
+ substate_token = _substate_key(client_token, substate)
+
+ if substate._get_was_touched():
+ substate._was_touched = False # Reset the touched flag after serializing.
+ pickle_state = substate._serialize()
+ if pickle_state:
+ if not self.states_directory.exists():
+ self.states_directory.mkdir(parents=True, exist_ok=True)
+ self.token_path(substate_token).write_bytes(pickle_state)
+
+ for substate_substate in substate.substates.values():
+ await self.set_state_for_substate(client_token, substate_substate)
+
+ @override
+ async def set_state(self, token: str, state: BaseState):
+ """Set the state for a token.
+
+ Args:
+ token: The token to set the state for.
+ state: The state to set.
+ """
+ client_token, substate = _split_substate_key(token)
+ await self.set_state_for_substate(client_token, state)
+
+ @override
+ @contextlib.asynccontextmanager
+ async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
+ """Modify the state for a token while holding exclusive lock.
+
+ Args:
+ token: The token to modify the state for.
+
+ Yields:
+ The state for the token.
+ """
+ # Memory state manager ignores the substate suffix and always returns the top-level state.
+ client_token, substate = _split_substate_key(token)
+ if client_token not in self._states_locks:
+ async with self._state_manager_lock:
+ if client_token not in self._states_locks:
+ self._states_locks[client_token] = asyncio.Lock()
+
+ async with self._states_locks[client_token]:
+ state = await self.get_state(token)
+ yield state
+ await self.set_state(token, state)
+
+
+def _default_lock_expiration() -> int:
+ """Get the default lock expiration time.
+
+ Returns:
+ The default lock expiration time.
+ """
+ return get_config().redis_lock_expiration
class StateManagerRedis(StateManager):
@@ -2287,10 +3054,10 @@ class StateManagerRedis(StateManager):
redis: Redis
# The token expiration time (s).
- token_expiration: int = constants.Expiration.TOKEN
+ token_expiration: int = pydantic.Field(default_factory=_default_token_expiration)
# The maximum time to hold a lock (ms).
- lock_expiration: int = constants.Expiration.LOCK
+ lock_expiration: int = pydantic.Field(default_factory=_default_lock_expiration)
# The keyspace subscription string when redis is waiting for lock to be released
_redis_notify_keyspace_events: str = (
@@ -2311,24 +3078,14 @@ class StateManagerRedis(StateManager):
# Only warn about each state class size once.
_warned_about_state_size: ClassVar[Set[str]] = set()
- def _get_root_state(self, state: BaseState) -> BaseState:
- """Chase parent_state pointers to find an instance of the top-level state.
-
- Args:
- state: The state to start from.
-
- Returns:
- An instance of the top-level state (self.state).
- """
- while type(state) != self.state and state.parent_state is not None:
- state = state.parent_state
- return state
-
- async def _get_parent_state(self, token: str) -> BaseState | None:
+ async def _get_parent_state(
+ self, token: str, state: BaseState | None = None
+ ) -> BaseState | None:
"""Get the parent state for the state requested in the token.
Args:
token: The token to get the state for (_substate_key).
+ state: The state instance to get parent state for.
Returns:
The parent state for the state requested by the token or None if there is no such parent.
@@ -2337,11 +3094,15 @@ class StateManagerRedis(StateManager):
client_token, state_path = _split_substate_key(token)
parent_state_name = state_path.rpartition(".")[0]
if parent_state_name:
+ cached_substates = None
+ if state is not None:
+ cached_substates = [state]
# Retrieve the parent state to populate event handlers onto this substate.
parent_state = await self.get_state(
token=_substate_key(client_token, parent_state_name),
top_level=False,
get_substates=False,
+ cached_substates=cached_substates,
)
return parent_state
@@ -2373,6 +3134,8 @@ class StateManagerRedis(StateManager):
tasks = {}
# Retrieve the necessary substates from redis.
for substate_cls in fetch_substates:
+ if substate_cls.get_name() in state.substates:
+ continue
substate_name = substate_cls.get_name()
tasks[substate_name] = asyncio.create_task(
self.get_state(
@@ -2386,12 +3149,14 @@ class StateManagerRedis(StateManager):
for substate_name, substate_task in tasks.items():
state.substates[substate_name] = await substate_task
+ @override
async def get_state(
self,
token: str,
top_level: bool = True,
get_substates: bool = True,
parent_state: BaseState | None = None,
+ cached_substates: list[BaseState] | None = None,
) -> BaseState:
"""Get the state for a token.
@@ -2400,6 +3165,7 @@ class StateManagerRedis(StateManager):
top_level: If true, return an instance of the top-level state (self.state).
get_substates: If true, also retrieve substates.
parent_state: If provided, use this parent_state instead of getting it from redis.
+ cached_substates: If provided, attach these substates to the state.
Returns:
The state for the token.
@@ -2417,49 +3183,42 @@ class StateManagerRedis(StateManager):
"StateManagerRedis requires token to be specified in the form of {token}_{state_full_name}"
)
+ # The deserialized or newly created (sub)state instance.
+ state = None
+
# Fetch the serialized substate from redis.
redis_state = await self.redis.get(token)
if redis_state is not None:
# Deserialize the substate.
- state = dill.loads(redis_state)
-
- # Populate parent state if missing and requested.
- if parent_state is None:
- parent_state = await self._get_parent_state(token)
- # Set up Bidirectional linkage between this state and its parent.
- if parent_state is not None:
- parent_state.substates[state.get_name()] = state
- state.parent_state = parent_state
- # Populate substates if requested.
- await self._populate_substates(token, state, all_substates=get_substates)
-
- # To retain compatibility with previous implementation, by default, we return
- # the top-level state by chasing `parent_state` pointers up the tree.
- if top_level:
- return self._get_root_state(state)
- return state
-
- # TODO: dedupe the following logic with the above block
- # Key didn't exist so we have to create a new instance for this token.
+ with contextlib.suppress(StateSchemaMismatchError):
+ state = BaseState._deserialize(data=redis_state)
+ if state is None:
+ # Key didn't exist or schema mismatch so create a new instance for this token.
+ state = state_cls(
+ init_substates=False,
+ _reflex_internal_init=True,
+ )
+ # Populate parent state if missing and requested.
if parent_state is None:
- parent_state = await self._get_parent_state(token)
- # Instantiate the new state class (but don't persist it yet).
- state = state_cls(
- parent_state=parent_state,
- init_substates=False,
- _reflex_internal_init=True,
- )
+ parent_state = await self._get_parent_state(token, state)
# Set up Bidirectional linkage between this state and its parent.
if parent_state is not None:
parent_state.substates[state.get_name()] = state
state.parent_state = parent_state
- # Populate substates for the newly created state.
+ # Avoid fetching substates multiple times.
+ if cached_substates:
+ for substate in cached_substates:
+ state.substates[substate.get_name()] = substate
+ if substate.parent_state is None:
+ substate.parent_state = state
+ # Populate substates if requested.
await self._populate_substates(token, state, all_substates=get_substates)
+
# To retain compatibility with previous implementation, by default, we return
# the top-level state by chasing `parent_state` pointers up the tree.
if top_level:
- return self._get_root_state(state)
+ return state._get_root_state()
return state
def _warn_if_too_large(
@@ -2485,6 +3244,7 @@ class StateManagerRedis(StateManager):
)
self._warned_about_state_size.add(state_full_name)
+ @override
async def set_state(
self,
token: str,
@@ -2510,7 +3270,7 @@ class StateManagerRedis(StateManager):
raise LockExpiredError(
f"Lock expired for token {token} while processing. Consider increasing "
f"`app.state_manager.lock_expiration` (currently {self.lock_expiration}) "
- "or use `@rx.background` decorator for long-running tasks."
+ "or use `@rx.event(background=True)` decorator for long-running tasks."
)
client_token, substate_name = _split_substate_key(token)
# If the substate name on the token doesn't match the instance name, it cannot have a parent.
@@ -2533,18 +3293,20 @@ class StateManagerRedis(StateManager):
)
# Persist only the given state (parents or substates are excluded by BaseState.__getstate__).
if state._get_was_touched():
- pickle_state = dill.dumps(state, byref=True)
+ pickle_state = state._serialize()
self._warn_if_too_large(state, len(pickle_state))
- await self.redis.set(
- _substate_key(client_token, state),
- pickle_state,
- ex=self.token_expiration,
- )
+ if pickle_state:
+ await self.redis.set(
+ _substate_key(client_token, state),
+ pickle_state,
+ ex=self.token_expiration,
+ )
# Wait for substates to be persisted.
for t in tasks:
await t
+ @override
@contextlib.asynccontextmanager
async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
"""Modify the state for a token while holding exclusive lock.
@@ -2599,13 +3361,22 @@ class StateManagerRedis(StateManager):
Args:
lock_key: The redis key for the lock.
lock_id: The ID of the lock.
+
+ Raises:
+ ResponseError: when the keyspace config cannot be set.
"""
state_is_locked = False
lock_key_channel = f"__keyspace@0__:{lock_key.decode()}"
# Enable keyspace notifications for the lock key, so we know when it is available.
- await self.redis.config_set(
- "notify-keyspace-events", self._redis_notify_keyspace_events
- )
+ try:
+ await self.redis.config_set(
+ "notify-keyspace-events",
+ self._redis_notify_keyspace_events,
+ )
+ except ResponseError:
+ # Some redis servers only allow out-of-band configuration, so ignore errors here.
+ if not environment.REFLEX_IGNORE_REDIS_CONFIG_ERROR:
+ raise
async with self.redis.pubsub() as pubsub:
await pubsub.psubscribe(lock_key_channel)
while not state_is_locked:
@@ -2676,111 +3447,6 @@ def get_state_manager() -> StateManager:
return app.state_manager
-class ClientStorageBase:
- """Base class for client-side storage."""
-
- def options(self) -> dict[str, Any]:
- """Get the options for the storage.
-
- Returns:
- All set options for the storage (not None).
- """
- return {
- format.to_camel_case(k): v for k, v in vars(self).items() if v is not None
- }
-
-
-class Cookie(ClientStorageBase, str):
- """Represents a state Var that is stored as a cookie in the browser."""
-
- name: str | None
- path: str
- max_age: int | None
- domain: str | None
- secure: bool | None
- same_site: str
-
- def __new__(
- cls,
- object: Any = "",
- encoding: str | None = None,
- errors: str | None = None,
- /,
- name: str | None = None,
- path: str = "/",
- max_age: int | None = None,
- domain: str | None = None,
- secure: bool | None = None,
- same_site: str = "lax",
- ):
- """Create a client-side Cookie (str).
-
- Args:
- object: The initial object.
- encoding: The encoding to use.
- errors: The error handling scheme to use.
- name: The name of the cookie on the client side.
- path: Cookie path. Use / as the path if the cookie should be accessible on all pages.
- max_age: Relative max age of the cookie in seconds from when the client receives it.
- domain: Domain for the cookie (sub.domain.com or .allsubdomains.com).
- secure: Is the cookie only accessible through HTTPS?
- same_site: Whether the cookie is sent with third party requests.
- One of (true|false|none|lax|strict)
-
- Returns:
- The client-side Cookie object.
-
- Note: expires (absolute Date) is not supported at this time.
- """
- if encoding or errors:
- inst = super().__new__(cls, object, encoding or "utf-8", errors or "strict")
- else:
- inst = super().__new__(cls, object)
- inst.name = name
- inst.path = path
- inst.max_age = max_age
- inst.domain = domain
- inst.secure = secure
- inst.same_site = same_site
- return inst
-
-
-class LocalStorage(ClientStorageBase, str):
- """Represents a state Var that is stored in localStorage in the browser."""
-
- name: str | None
- sync: bool = False
-
- def __new__(
- cls,
- object: Any = "",
- encoding: str | None = None,
- errors: str | None = None,
- /,
- name: str | None = None,
- sync: bool = False,
- ) -> "LocalStorage":
- """Create a client-side localStorage (str).
-
- Args:
- object: The initial object.
- encoding: The encoding to use.
- errors: The error handling scheme to use.
- name: The name of the storage key on the client side.
- sync: Whether changes should be propagated to other tabs.
-
- Returns:
- The client-side localStorage object.
- """
- if encoding or errors:
- inst = super().__new__(cls, object, encoding or "utf-8", errors or "strict")
- else:
- inst = super().__new__(cls, object)
- inst.name = name
- inst.sync = sync
- return inst
-
-
class MutableProxy(wrapt.ObjectProxy):
"""A proxy for a mutable object that tracks changes."""
@@ -2813,7 +3479,12 @@ class MutableProxy(wrapt.ObjectProxy):
]
)
- __mutable_types__ = (list, dict, set, Base)
+ # These internal attributes on rx.Base should NOT be wrapped in a MutableProxy.
+ __never_wrap_base_attrs__ = set(Base.__dict__) - {"set"} | set(
+ pydantic.BaseModel.__dict__
+ )
+
+ __mutable_types__ = (list, dict, set, Base, DeclarativeBase)
def __init__(self, wrapped: Any, state: BaseState, field_name: str):
"""Create a proxy for a mutable object that tracks changes.
@@ -2862,7 +3533,10 @@ class MutableProxy(wrapt.ObjectProxy):
Returns:
The wrapped value.
"""
- if isinstance(value, self.__mutable_types__):
+ # Recursively wrap mutable types, but do not re-wrap MutableProxy instances.
+ if isinstance(value, self.__mutable_types__) and not isinstance(
+ value, MutableProxy
+ ):
return type(self)(
wrapped=value,
state=self._self_state,
@@ -2909,6 +3583,17 @@ class MutableProxy(wrapt.ObjectProxy):
self._wrap_recursive_decorator,
)
+ if (
+ isinstance(self.__wrapped__, Base)
+ and __name not in self.__never_wrap_base_attrs__
+ and hasattr(value, "__func__")
+ ):
+ # Wrap methods called on Base subclasses, which might do _anything_
+ return wrapt.FunctionWrapper(
+ functools.partial(value.__func__, self),
+ self._wrap_recursive_decorator,
+ )
+
if isinstance(value, self.__mutable_types__) and __name not in (
"__wrapped__",
"_self_state",
@@ -3018,22 +3703,16 @@ class MutableProxy(wrapt.ObjectProxy):
@serializer
-def serialize_mutable_proxy(mp: MutableProxy) -> SerializedType:
- """Serialize the wrapped value of a MutableProxy.
+def serialize_mutable_proxy(mp: MutableProxy):
+ """Return the wrapped value of a MutableProxy.
Args:
mp: The MutableProxy to serialize.
Returns:
- The serialized wrapped object.
-
- Raises:
- ValueError: when the wrapped object is not serializable.
+ The wrapped object.
"""
- value = serialize(mp.__wrapped__)
- if value is None:
- raise ValueError(f"Cannot serialize {type(mp.__wrapped__)}")
- return value
+ return mp.__wrapped__
class ImmutableMutableProxy(MutableProxy):
@@ -3066,7 +3745,7 @@ class ImmutableMutableProxy(MutableProxy):
Raises:
ImmutableStateError: if the StateProxy is not mutable.
"""
- if not self._self_state._self_mutable:
+ if not self._self_state._is_mutable():
raise ImmutableStateError(
"Background task StateProxy is immutable outside of a context "
"manager. Use `async with self` to modify state."
@@ -3104,5 +3783,7 @@ def reload_state_module(
if subclass.__module__ == module and module is not None:
state.class_subclasses.remove(subclass)
state._always_dirty_substates.discard(subclass.get_name())
- state._init_var_dependency_dicts()
+ state._computed_var_dependencies = defaultdict(set)
+ state._substate_var_dependencies = defaultdict(set)
+ state._init_var_dependency_dicts()
state.get_class_substate.cache_clear()
diff --git a/reflex/style.py b/reflex/style.py
index e48aa3dd8..f0ee8c6a7 100644
--- a/reflex/style.py
+++ b/reflex/style.py
@@ -2,43 +2,94 @@
from __future__ import annotations
-from typing import Any, Tuple
+from typing import Any, Literal, Tuple, Type
from reflex import constants
-from reflex.event import EventChain
+from reflex.components.core.breakpoints import Breakpoints, breakpoints_values
+from reflex.event import EventChain, EventHandler
from reflex.utils import format
+from reflex.utils.exceptions import ReflexError
from reflex.utils.imports import ImportVar
-from reflex.vars import BaseVar, Var, VarData
-
-VarData.update_forward_refs() # Ensure all type definitions are resolved
+from reflex.utils.types import get_origin
+from reflex.vars import VarData
+from reflex.vars.base import CallableVar, LiteralVar, Var
+from reflex.vars.function import FunctionVar
+from reflex.vars.object import ObjectVar
+SYSTEM_COLOR_MODE: str = "system"
LIGHT_COLOR_MODE: str = "light"
DARK_COLOR_MODE: str = "dark"
+LiteralColorMode = Literal["system", "light", "dark"]
# Reference the global ColorModeContext
-color_mode_var_data = VarData( # type: ignore
- imports={
- f"/{constants.Dirs.CONTEXTS_PATH}": {ImportVar(tag="ColorModeContext")},
- "react": {ImportVar(tag="useContext")},
- },
- hooks={
- f"const [ {constants.ColorMode.NAME}, {constants.ColorMode.TOGGLE} ] = useContext(ColorModeContext)": None,
- },
-)
-# Var resolves to the current color mode for the app ("light" or "dark")
-color_mode = BaseVar(
- _var_name=constants.ColorMode.NAME,
- _var_type="str",
- _var_data=color_mode_var_data,
-)
-# Var resolves to a function invocation that toggles the color mode
-toggle_color_mode = BaseVar(
- _var_name=constants.ColorMode.TOGGLE,
- _var_type=EventChain,
- _var_data=color_mode_var_data,
-)
+color_mode_imports = {
+ f"$/{constants.Dirs.CONTEXTS_PATH}": [ImportVar(tag="ColorModeContext")],
+ "react": [ImportVar(tag="useContext")],
+}
-breakpoints = ["0", "30em", "48em", "62em", "80em", "96em"]
+
+def _color_mode_var(_js_expr: str, _var_type: Type = str) -> Var:
+ """Create a Var that destructs the _js_expr from ColorModeContext.
+
+ Args:
+ _js_expr: The name of the variable to get from ColorModeContext.
+ _var_type: The type of the Var.
+
+ Returns:
+ The Var that resolves to the color mode.
+ """
+ return Var(
+ _js_expr=_js_expr,
+ _var_type=_var_type,
+ _var_data=VarData(
+ imports=color_mode_imports,
+ hooks={f"const {{ {_js_expr} }} = useContext(ColorModeContext)": None},
+ ),
+ ).guess_type()
+
+
+@CallableVar
+def set_color_mode(
+ new_color_mode: LiteralColorMode | Var[LiteralColorMode] | None = None,
+) -> Var[EventChain]:
+ """Create an EventChain Var that sets the color mode to a specific value.
+
+ Note: `set_color_mode` is not a real event and cannot be triggered from a
+ backend event handler.
+
+ Args:
+ new_color_mode: The color mode to set.
+
+ Returns:
+ The EventChain Var that can be passed to an event trigger.
+ """
+ base_setter = _color_mode_var(
+ _js_expr=constants.ColorMode.SET,
+ _var_type=EventChain,
+ )
+ if new_color_mode is None:
+ return base_setter
+
+ if not isinstance(new_color_mode, Var):
+ new_color_mode = LiteralVar.create(new_color_mode)
+
+ return Var(
+ f"() => {str(base_setter)}({str(new_color_mode)})",
+ _var_data=VarData.merge(
+ base_setter._get_all_var_data(), new_color_mode._get_all_var_data()
+ ),
+ ).to(FunctionVar, EventChain) # type: ignore
+
+
+# Var resolves to the current color mode for the app ("light", "dark" or "system")
+color_mode = _color_mode_var(_js_expr=constants.ColorMode.NAME)
+# Var resolves to the resolved color mode for the app ("light" or "dark")
+resolved_color_mode = _color_mode_var(_js_expr=constants.ColorMode.RESOLVED_NAME)
+# Var resolves to a function invocation that toggles the color mode
+toggle_color_mode = _color_mode_var(
+ _js_expr=constants.ColorMode.TOGGLE,
+ _var_type=EventChain,
+)
STYLE_PROP_SHORTHAND_MAPPING = {
"paddingX": ("paddingInlineStart", "paddingInlineEnd"),
@@ -47,22 +98,26 @@ STYLE_PROP_SHORTHAND_MAPPING = {
"marginY": ("marginTop", "marginBottom"),
"bg": ("background",),
"bgColor": ("backgroundColor",),
+ # Radix components derive their font from this CSS var, not inherited from body or class.
+ "fontFamily": ("fontFamily", "--default-font-family"),
}
-def media_query(breakpoint_index: int):
+def media_query(breakpoint_expr: str):
"""Create a media query selector.
Args:
- breakpoint_index: The index of the breakpoint to use.
+ breakpoint_expr: The CSS expression representing the breakpoint.
Returns:
The media query selector used as a key in emotion css dict.
"""
- return f"@media screen and (min-width: {breakpoints[breakpoint_index]})"
+ return f"@media screen and (min-width: {breakpoint_expr})"
-def convert_item(style_item: str | Var) -> tuple[str, VarData | None]:
+def convert_item(
+ style_item: int | str | Var,
+) -> tuple[str | Var, VarData | None]:
"""Format a single value in a style dictionary.
Args:
@@ -70,23 +125,31 @@ def convert_item(style_item: str | Var) -> tuple[str, VarData | None]:
Returns:
The formatted style item and any associated VarData.
+
+ Raises:
+ ReflexError: If an EventHandler is used as a style value
"""
+ if isinstance(style_item, EventHandler):
+ raise ReflexError(
+ "EventHandlers cannot be used as style values. "
+ "Please use a Var or a literal value."
+ )
+
if isinstance(style_item, Var):
- # If the value is a Var, extract the var_data and cast as str.
- return str(style_item), style_item._var_data
+ return style_item, style_item._get_all_var_data()
+
+ # if isinstance(style_item, str) and REFLEX_VAR_OPENING_TAG not in style_item:
+ # return style_item, None
# Otherwise, convert to Var to collapse VarData encoded in f-string.
- new_var = Var.create(style_item)
- if new_var is not None and new_var._var_data:
- # The wrapped backtick is used to identify the Var for interpolation.
- return f"`{str(new_var)}`", new_var._var_data
-
- return style_item, None
+ new_var = LiteralVar.create(style_item)
+ var_data = new_var._get_all_var_data() if new_var is not None else None
+ return new_var, var_data
def convert_list(
responsive_list: list[str | dict | Var],
-) -> tuple[list[str | dict], VarData | None]:
+) -> tuple[list[str | dict[str, Var | list | dict]], VarData | None]:
"""Format a responsive value list.
Args:
@@ -108,7 +171,9 @@ def convert_list(
return converted_value, VarData.merge(*item_var_datas)
-def convert(style_dict):
+def convert(
+ style_dict: dict[str, Var | dict | list | str],
+) -> tuple[dict[str, str | list | dict], VarData | None]:
"""Format a style dictionary.
Args:
@@ -125,8 +190,25 @@ def convert(style_dict):
out[k] = return_value
for key, value in style_dict.items():
- keys = format_style_key(key)
- if isinstance(value, dict):
+ keys = (
+ format_style_key(key)
+ if not isinstance(value, (dict, ObjectVar))
+ or (
+ isinstance(value, Breakpoints)
+ and all(not isinstance(v, dict) for v in value.values())
+ )
+ or (
+ isinstance(value, ObjectVar)
+ and not issubclass(get_origin(value._var_type) or value._var_type, dict)
+ )
+ else (key,)
+ )
+
+ if isinstance(value, Var):
+ return_val = value
+ new_var_data = value._get_all_var_data()
+ update_out_dict(return_val, keys)
+ elif isinstance(value, dict):
# Recursively format nested style dictionaries.
return_val, new_var_data = convert(value)
update_out_dict(return_val, keys)
@@ -139,6 +221,10 @@ def convert(style_dict):
update_out_dict(return_val, keys)
# Combine all the collected VarData instances.
var_data = VarData.merge(var_data, new_var_data)
+
+ if isinstance(style_dict, Breakpoints):
+ out = Breakpoints(out).factorize()
+
return out, var_data
@@ -201,10 +287,10 @@ class Style(dict):
value: The value to set.
"""
# Create a Var to collapse VarData encoded in f-string.
- _var = Var.create(value)
+ _var = LiteralVar.create(value)
if _var is not None:
# Carry the imports/hooks when setting a Var as a value.
- self._var_data = VarData.merge(self._var_data, _var._var_data)
+ self._var_data = VarData.merge(self._var_data, _var._get_all_var_data())
super().__setitem__(key, value)
@@ -212,14 +298,13 @@ def _format_emotion_style_pseudo_selector(key: str) -> str:
"""Format a pseudo selector for emotion CSS-in-JS.
Args:
- key: Underscore-prefixed or colon-prefixed pseudo selector key (_hover).
+ key: Underscore-prefixed or colon-prefixed pseudo selector key (_hover/:hover).
Returns:
A self-referential pseudo selector key (&:hover).
"""
prefix = None
if key.startswith("_"):
- # Handle pseudo selectors in chakra style format.
prefix = "&:"
key = key[1:]
if key.startswith(":"):
@@ -245,14 +330,22 @@ def format_as_emotion(style_dict: dict[str, Any]) -> Style | None:
for orig_key, value in style_dict.items():
key = _format_emotion_style_pseudo_selector(orig_key)
- if isinstance(value, list):
- # Apply media queries from responsive value list.
- mbps = {
- media_query(bp): (
- bp_value if isinstance(bp_value, dict) else {key: bp_value}
- )
- for bp, bp_value in enumerate(value)
- }
+ if isinstance(value, (Breakpoints, list)):
+ if isinstance(value, Breakpoints):
+ mbps = {
+ media_query(bp): (
+ bp_value if isinstance(bp_value, dict) else {key: bp_value}
+ )
+ for bp, bp_value in value.items()
+ }
+ else:
+ # Apply media queries from responsive value list.
+ mbps = {
+ media_query([0, *breakpoints_values][bp]): (
+ bp_value if isinstance(bp_value, dict) else {key: bp_value}
+ )
+ for bp, bp_value in enumerate(value)
+ }
if key.startswith("&:"):
emotion_style[key] = mbps
else:
@@ -270,7 +363,7 @@ def format_as_emotion(style_dict: dict[str, Any]) -> Style | None:
def convert_dict_to_style_and_format_emotion(
- raw_dict: dict[str, Any]
+ raw_dict: dict[str, Any],
) -> dict[str, Any] | None:
"""Convert a dict to a style dict and then format as emotion.
diff --git a/reflex/testing.py b/reflex/testing.py
index 5613af333..b41e56884 100644
--- a/reflex/testing.py
+++ b/reflex/testing.py
@@ -26,6 +26,7 @@ from typing import (
AsyncIterator,
Callable,
Coroutine,
+ List,
Optional,
Type,
TypeVar,
@@ -39,10 +40,13 @@ import reflex
import reflex.reflex
import reflex.utils.build
import reflex.utils.exec
+import reflex.utils.format
import reflex.utils.prerequisites
import reflex.utils.processes
from reflex.state import (
BaseState,
+ StateManager,
+ StateManagerDisk,
StateManagerMemory,
StateManagerRedis,
reload_state_module,
@@ -113,7 +117,7 @@ class AppHarness:
app_name: str
app_source: Optional[
- types.FunctionType | types.ModuleType | str | functools.partial
+ types.FunctionType | types.ModuleType | str | functools.partial[Any]
]
app_path: pathlib.Path
app_module_path: pathlib.Path
@@ -124,7 +128,7 @@ class AppHarness:
frontend_output_thread: Optional[threading.Thread] = None
backend_thread: Optional[threading.Thread] = None
backend: Optional[uvicorn.Server] = None
- state_manager: Optional[StateManagerMemory | StateManagerRedis] = None
+ state_manager: Optional[StateManager] = None
_frontends: list["WebDriver"] = dataclasses.field(default_factory=list)
_decorated_pages: list = dataclasses.field(default_factory=list)
@@ -132,7 +136,9 @@ class AppHarness:
def create(
cls,
root: pathlib.Path,
- app_source: Optional[types.FunctionType | types.ModuleType | str] = None,
+ app_source: Optional[
+ types.FunctionType | types.ModuleType | str | functools.partial[Any]
+ ] = None,
app_name: Optional[str] = None,
) -> "AppHarness":
"""Create an AppHarness instance at root.
@@ -176,6 +182,33 @@ class AppHarness:
app_module_path=root / app_name / f"{app_name}.py",
)
+ def get_state_name(self, state_cls_name: str) -> str:
+ """Get the state name for the given state class name.
+
+ Args:
+ state_cls_name: The state class name
+
+ Returns:
+ The state name
+ """
+ return reflex.utils.format.to_snake_case(
+ f"{self.app_name}___{self.app_name}___" + state_cls_name
+ )
+
+ def get_full_state_name(self, path: List[str]) -> str:
+ """Get the full state name for the given state class name.
+
+ Args:
+ path: A list of state class names
+
+ Returns:
+ The full state name
+ """
+ # NOTE: using State.get_name() somehow causes trouble here
+ # path = [State.get_name()] + [self.get_state_name(p) for p in path]
+ path = ["reflex___state____state"] + [self.get_state_name(p) for p in path]
+ return ".".join(path)
+
def _get_globals_from_signature(self, func: Any) -> dict[str, Any]:
"""Get the globals from a function or module object.
@@ -216,7 +249,8 @@ class AppHarness:
return textwrap.dedent(source)
def _initialize_app(self):
- os.environ["TELEMETRY_ENABLED"] = "" # disable telemetry reporting for tests
+ # disable telemetry reporting for tests
+ os.environ["TELEMETRY_ENABLED"] = "false"
self.app_path.mkdir(parents=True, exist_ok=True)
if self.app_source is not None:
app_globals = self._get_globals_from_signature(self.app_source)
@@ -245,7 +279,10 @@ class AppHarness:
before_decorated_pages = reflex.app.DECORATED_PAGES[self.app_name].copy()
# Ensure the AppHarness test does not skip State assignment due to running via pytest
os.environ.pop(reflex.constants.PYTEST_CURRENT_TEST, None)
- self.app_module = reflex.utils.prerequisites.get_compiled_app(reload=True)
+ self.app_module = reflex.utils.prerequisites.get_compiled_app(
+ # Do not reload the module for pre-existing apps (only apps generated from source)
+ reload=self.app_source is not None
+ )
# Save the pages that were added during testing
self._decorated_pages = [
p
@@ -293,9 +330,35 @@ class AppHarness:
)
)
self.backend.shutdown = self._get_backend_shutdown_handler()
- self.backend_thread = threading.Thread(target=self.backend.run)
+ with chdir(self.app_path):
+ self.backend_thread = threading.Thread(target=self.backend.run)
self.backend_thread.start()
+ async def _reset_backend_state_manager(self):
+ """Reset the StateManagerRedis event loop affinity.
+
+ This is necessary when the backend is restarted and the state manager is a
+ StateManagerRedis instance.
+
+ Raises:
+ RuntimeError: when the state manager cannot be reset
+ """
+ if (
+ self.app_instance is not None
+ and isinstance(
+ self.app_instance.state_manager,
+ StateManagerRedis,
+ )
+ and self.app_instance.state is not None
+ ):
+ with contextlib.suppress(RuntimeError):
+ await self.app_instance.state_manager.close()
+ self.app_instance._state_manager = StateManagerRedis.create(
+ state=self.app_instance.state,
+ )
+ if not isinstance(self.app_instance.state_manager, StateManagerRedis):
+ raise RuntimeError("Failed to reset state manager.")
+
def _start_frontend(self):
# Set up the frontend.
with chdir(self.app_path):
@@ -308,7 +371,7 @@ class AppHarness:
# Start the frontend.
self.frontend_process = reflex.utils.processes.new_process(
[reflex.utils.prerequisites.get_package_manager(), "run", "dev"],
- cwd=self.app_path / reflex.constants.Dirs.WEB,
+ cwd=self.app_path / reflex.utils.prerequisites.get_web_dir(),
env={"PORT": "0"},
**FRONTEND_POPEN_ARGS,
)
@@ -324,15 +387,22 @@ class AppHarness:
m = re.search(reflex.constants.Next.FRONTEND_LISTENING_REGEX, line)
if m is not None:
self.frontend_url = m.group(1)
+ config = reflex.config.get_config()
+ config.deploy_url = self.frontend_url
break
if self.frontend_url is None:
raise RuntimeError("Frontend did not start")
def consume_frontend_output():
while True:
- line = (
- self.frontend_process.stdout.readline() # pyright: ignore [reportOptionalMemberAccess]
- )
+ try:
+ line = (
+ self.frontend_process.stdout.readline() # pyright: ignore [reportOptionalMemberAccess]
+ )
+ # catch I/O operation on closed file.
+ except ValueError as e:
+ print(e)
+ break
if not line:
break
print(line)
@@ -513,12 +583,23 @@ class AppHarness:
raise TimeoutError("Backend is not listening.")
return backend.servers[0].sockets[0]
- def frontend(self, driver_clz: Optional[Type["WebDriver"]] = None) -> "WebDriver":
+ def frontend(
+ self,
+ driver_clz: Optional[Type["WebDriver"]] = None,
+ driver_kwargs: dict[str, Any] | None = None,
+ driver_options: ArgOptions | None = None,
+ driver_option_args: List[str] | None = None,
+ driver_option_capabilities: dict[str, Any] | None = None,
+ ) -> "WebDriver":
"""Get a selenium webdriver instance pointed at the app.
Args:
driver_clz: webdriver.Chrome (default), webdriver.Firefox, webdriver.Safari,
webdriver.Edge, etc
+ driver_kwargs: additional keyword arguments to pass to the webdriver constructor
+ driver_options: selenium ArgOptions instance to pass to the webdriver constructor
+ driver_option_args: additional arguments for the webdriver options
+ driver_option_capabilities: additional capabilities for the webdriver options
Returns:
Instance of the given webdriver navigated to the frontend url of the app.
@@ -534,26 +615,43 @@ class AppHarness:
if self.frontend_url is None:
raise RuntimeError("Frontend is not running.")
want_headless = False
- options: ArgOptions | None = None
if os.environ.get("APP_HARNESS_HEADLESS"):
want_headless = True
if driver_clz is None:
requested_driver = os.environ.get("APP_HARNESS_DRIVER", "Chrome")
driver_clz = getattr(webdriver, requested_driver)
- options = getattr(webdriver, f"{requested_driver}Options")()
- if driver_clz is webdriver.Chrome and want_headless:
- options = webdriver.ChromeOptions()
- options.add_argument("--headless=new")
- elif driver_clz is webdriver.Firefox and want_headless:
- options = webdriver.FirefoxOptions()
- options.add_argument("-headless")
- elif driver_clz is webdriver.Edge and want_headless:
- options = webdriver.EdgeOptions()
- options.add_argument("headless")
- if options and (args := os.environ.get("APP_HARNESS_DRIVER_ARGS")):
+ if driver_options is None:
+ driver_options = getattr(webdriver, f"{requested_driver}Options")()
+ if driver_clz is webdriver.Chrome:
+ if driver_options is None:
+ driver_options = webdriver.ChromeOptions()
+ driver_options.add_argument("--class=AppHarness")
+ if want_headless:
+ driver_options.add_argument("--headless=new")
+ elif driver_clz is webdriver.Firefox:
+ if driver_options is None:
+ driver_options = webdriver.FirefoxOptions()
+ if want_headless:
+ driver_options.add_argument("-headless")
+ elif driver_clz is webdriver.Edge:
+ if driver_options is None:
+ driver_options = webdriver.EdgeOptions()
+ if want_headless:
+ driver_options.add_argument("headless")
+ if driver_options is None:
+ raise RuntimeError(f"Could not determine options for {driver_clz}")
+ if args := os.environ.get("APP_HARNESS_DRIVER_ARGS"):
for arg in args.split(","):
- options.add_argument(arg)
- driver = driver_clz(options=options) # type: ignore
+ driver_options.add_argument(arg)
+ if driver_option_args is not None:
+ for arg in driver_option_args:
+ driver_options.add_argument(arg)
+ if driver_option_capabilities is not None:
+ for key, value in driver_option_capabilities.items():
+ driver_options.set_capability(key, value)
+ if driver_kwargs is None:
+ driver_kwargs = {}
+ driver = driver_clz(options=driver_options, **driver_kwargs) # type: ignore
driver.get(self.frontend_url)
self._frontends.append(driver)
return driver
@@ -697,13 +795,13 @@ class AppHarness:
Raises:
RuntimeError: when the app hasn't started running
TimeoutError: when the timeout expires before any states are seen
+ ValueError: when the state_manager is not a memory state manager
"""
if self.app_instance is None:
raise RuntimeError("App is not running.")
state_manager = self.app_instance.state_manager
- assert isinstance(
- state_manager, StateManagerMemory
- ), "Only works with memory state manager"
+ if not isinstance(state_manager, (StateManagerMemory, StateManagerDisk)):
+ raise ValueError("Only works with memory or disk state manager")
if not self._poll_for(
target=lambda: state_manager.states,
timeout=timeout,
@@ -802,7 +900,11 @@ class AppHarnessProd(AppHarness):
frontend_server: Optional[Subdir404TCPServer] = None
def _run_frontend(self):
- web_root = self.app_path / reflex.constants.Dirs.WEB_STATIC
+ web_root = (
+ self.app_path
+ / reflex.utils.prerequisites.get_web_dir()
+ / reflex.constants.Dirs.STATIC
+ )
error_page_map = {
404: web_root / "404.html",
}
diff --git a/reflex/utils/build.py b/reflex/utils/build.py
index 65bb8b04c..14709d99c 100644
--- a/reflex/utils/build.py
+++ b/reflex/utils/build.py
@@ -18,23 +18,11 @@ from reflex.utils import console, path_ops, prerequisites, processes
def set_env_json():
"""Write the upload url to a REFLEX_JSON."""
path_ops.update_json_file(
- constants.Dirs.ENV_JSON,
+ str(prerequisites.get_web_dir() / constants.Dirs.ENV_JSON),
{endpoint.name: endpoint.get_url() for endpoint in constants.Endpoint},
)
-def set_os_env(**kwargs):
- """Set os environment variables.
-
- Args:
- kwargs: env key word args.
- """
- for key, value in kwargs.items():
- if not value:
- continue
- os.environ[key.upper()] = value
-
-
def generate_sitemap_config(deploy_url: str, export=False):
"""Generate the sitemap config file.
@@ -55,14 +43,14 @@ def generate_sitemap_config(deploy_url: str, export=False):
config = json.dumps(config)
- with open(constants.Next.SITEMAP_CONFIG_FILE, "w") as f:
- f.write(templates.SITEMAP_CONFIG(config=config))
+ sitemap = prerequisites.get_web_dir() / constants.Next.SITEMAP_CONFIG_FILE
+ sitemap.write_text(templates.SITEMAP_CONFIG(config=config))
def _zip(
component_name: constants.ComponentName,
- target: str,
- root_dir: str,
+ target: str | Path,
+ root_dir: str | Path,
exclude_venv_dirs: bool,
upload_db_file: bool = False,
dirs_to_exclude: set[str] | None = None,
@@ -82,22 +70,22 @@ def _zip(
top_level_dirs_to_exclude: The top level directory names immediately under root_dir to exclude. Do not exclude folders by these names further in the sub-directories.
"""
+ target = Path(target)
+ root_dir = Path(root_dir)
dirs_to_exclude = dirs_to_exclude or set()
files_to_exclude = files_to_exclude or set()
files_to_zip: list[str] = []
# Traverse the root directory in a top-down manner. In this traversal order,
# we can modify the dirs list in-place to remove directories we don't want to include.
for root, dirs, files in os.walk(root_dir, topdown=True):
+ root = Path(root)
# Modify the dirs in-place so excluded and hidden directories are skipped in next traversal.
dirs[:] = [
d
for d in dirs
- if (basename := os.path.basename(os.path.normpath(d)))
- not in dirs_to_exclude
+ if (basename := Path(d).resolve().name) not in dirs_to_exclude
and not basename.startswith(".")
- and (
- not exclude_venv_dirs or not _looks_like_venv_dir(os.path.join(root, d))
- )
+ and (not exclude_venv_dirs or not _looks_like_venv_dir(root / d))
]
# If we are at the top level with root_dir, exclude the top level dirs.
if top_level_dirs_to_exclude and root == root_dir:
@@ -109,7 +97,7 @@ def _zip(
if not f.startswith(".") and (upload_db_file or not f.endswith(".db"))
]
files_to_zip += [
- os.path.join(root, file) for file in files if file not in files_to_exclude
+ str(root / file) for file in files if file not in files_to_exclude
]
# Create a progress bar for zipping the component.
@@ -126,88 +114,93 @@ def _zip(
for file in files_to_zip:
console.debug(f"{target}: {file}", progress=progress)
progress.advance(task)
- zipf.write(file, os.path.relpath(file, root_dir))
+ zipf.write(file, Path(file).relative_to(root_dir))
-def export(
- backend: bool = True,
+def zip_app(
frontend: bool = True,
- zip: bool = False,
- zip_dest_dir: str = os.getcwd(),
- deploy_url: str | None = None,
+ backend: bool = True,
+ zip_dest_dir: str | Path = Path.cwd(),
upload_db_file: bool = False,
):
- """Export the app for deployment.
+ """Zip up the app.
Args:
- backend: Whether to zip up the backend app.
frontend: Whether to zip up the frontend app.
- zip: Whether to zip the app.
- zip_dest_dir: The destination directory for created zip files (if any)
- deploy_url: The URL of the deployed app.
- upload_db_file: Whether to include local sqlite db files from the backend zip.
+ backend: Whether to zip up the backend app.
+ zip_dest_dir: The directory to export the zip file to.
+ upload_db_file: Whether to upload the database file.
"""
- # Remove the static folder.
- path_ops.rm(constants.Dirs.WEB_STATIC)
+ zip_dest_dir = Path(zip_dest_dir)
+ files_to_exclude = {
+ constants.ComponentName.FRONTEND.zip(),
+ constants.ComponentName.BACKEND.zip(),
+ }
+
+ if frontend:
+ _zip(
+ component_name=constants.ComponentName.FRONTEND,
+ target=zip_dest_dir / constants.ComponentName.FRONTEND.zip(),
+ root_dir=prerequisites.get_web_dir() / constants.Dirs.STATIC,
+ files_to_exclude=files_to_exclude,
+ exclude_venv_dirs=False,
+ )
+
+ if backend:
+ _zip(
+ component_name=constants.ComponentName.BACKEND,
+ target=zip_dest_dir / constants.ComponentName.BACKEND.zip(),
+ root_dir=Path("."),
+ dirs_to_exclude={"__pycache__"},
+ files_to_exclude=files_to_exclude,
+ top_level_dirs_to_exclude={"assets"},
+ exclude_venv_dirs=True,
+ upload_db_file=upload_db_file,
+ )
+
+
+def build(
+ deploy_url: str | None = None,
+ for_export: bool = False,
+):
+ """Build the app for deployment.
+
+ Args:
+ deploy_url: The deployment URL.
+ for_export: Whether the build is for export.
+ """
+ wdir = prerequisites.get_web_dir()
+
+ # Clean the static directory if it exists.
+ path_ops.rm(str(wdir / constants.Dirs.STATIC))
# The export command to run.
command = "export"
- if frontend:
- checkpoints = [
- "Linting and checking ",
- "Creating an optimized production build",
- "Route (pages)",
- "prerendered as static HTML",
- "Collecting page data",
- "Finalizing page optimization",
- "Collecting build traces",
- ]
+ checkpoints = [
+ "Linting and checking ",
+ "Creating an optimized production build",
+ "Route (pages)",
+ "prerendered as static HTML",
+ "Collecting page data",
+ "Finalizing page optimization",
+ "Collecting build traces",
+ ]
- # Generate a sitemap if a deploy URL is provided.
- if deploy_url is not None:
- generate_sitemap_config(deploy_url, export=zip)
- command = "export-sitemap"
+ # Generate a sitemap if a deploy URL is provided.
+ if deploy_url is not None:
+ generate_sitemap_config(deploy_url, export=for_export)
+ command = "export-sitemap"
- checkpoints.extend(["Loading next-sitemap", "Generation completed"])
+ checkpoints.extend(["Loading next-sitemap", "Generation completed"])
- # Start the subprocess with the progress bar.
- process = processes.new_process(
- [prerequisites.get_package_manager(), "run", command],
- cwd=constants.Dirs.WEB,
- shell=constants.IS_WINDOWS,
- )
- processes.show_progress("Creating Production Build", process, checkpoints)
-
- # Zip up the app.
- if zip:
- files_to_exclude = {
- constants.ComponentName.FRONTEND.zip(),
- constants.ComponentName.BACKEND.zip(),
- }
- if frontend:
- _zip(
- component_name=constants.ComponentName.FRONTEND,
- target=os.path.join(
- zip_dest_dir, constants.ComponentName.FRONTEND.zip()
- ),
- root_dir=constants.Dirs.WEB_STATIC,
- files_to_exclude=files_to_exclude,
- exclude_venv_dirs=False,
- )
- if backend:
- _zip(
- component_name=constants.ComponentName.BACKEND,
- target=os.path.join(
- zip_dest_dir, constants.ComponentName.BACKEND.zip()
- ),
- root_dir=".",
- dirs_to_exclude={"__pycache__"},
- files_to_exclude=files_to_exclude,
- top_level_dirs_to_exclude={"assets"},
- exclude_venv_dirs=True,
- upload_db_file=upload_db_file,
- )
+ # Start the subprocess with the progress bar.
+ process = processes.new_process(
+ [prerequisites.get_package_manager(), "run", command],
+ cwd=wdir,
+ shell=constants.IS_WINDOWS,
+ )
+ processes.show_progress("Creating Production Build", process, checkpoints)
def setup_frontend(
@@ -226,12 +219,15 @@ def setup_frontend(
# Copy asset files to public folder.
path_ops.cp(
src=str(root / constants.Dirs.APP_ASSETS),
- dest=str(root / constants.Dirs.WEB_ASSETS),
+ dest=str(root / prerequisites.get_web_dir() / constants.Dirs.PUBLIC),
)
# Set the environment variables in client (env.json).
set_env_json()
+ # update the last reflex run time.
+ prerequisites.set_last_reflex_run_time()
+
# Disable the Next telemetry.
if disable_telemetry:
processes.new_process(
@@ -242,7 +238,7 @@ def setup_frontend(
"telemetry",
"disable",
],
- cwd=constants.Dirs.WEB,
+ cwd=prerequisites.get_web_dir(),
stdout=subprocess.DEVNULL,
shell=constants.IS_WINDOWS,
)
@@ -259,8 +255,9 @@ def setup_frontend_prod(
disable_telemetry: Whether to disable the Next telemetry.
"""
setup_frontend(root, disable_telemetry)
- export(deploy_url=get_config().deploy_url)
+ build(deploy_url=get_config().deploy_url)
-def _looks_like_venv_dir(dir_to_check: str) -> bool:
- return os.path.exists(os.path.join(dir_to_check, "pyvenv.cfg"))
+def _looks_like_venv_dir(dir_to_check: str | Path) -> bool:
+ dir_to_check = Path(dir_to_check)
+ return (dir_to_check / "pyvenv.cfg").exists()
diff --git a/reflex/utils/codespaces.py b/reflex/utils/codespaces.py
new file mode 100644
index 000000000..7ff686129
--- /dev/null
+++ b/reflex/utils/codespaces.py
@@ -0,0 +1,94 @@
+"""Utilities for working with Github Codespaces."""
+
+from __future__ import annotations
+
+import os
+
+from fastapi.responses import HTMLResponse
+
+from reflex.components.base.script import Script
+from reflex.components.component import Component
+from reflex.components.core.banner import has_connection_errors
+from reflex.components.core.cond import cond
+from reflex.constants import Endpoint
+
+redirect_script = """
+const thisUrl = new URL(window.location.href);
+const params = new URLSearchParams(thisUrl.search)
+
+function doRedirect(url) {
+ if (!window.sessionStorage.getItem("authenticated_github_codespaces")) {
+ const a = document.createElement("a");
+ if (params.has("redirect_to")) {
+ a.href = params.get("redirect_to")
+ } else if (!window.location.href.startsWith(url)) {
+ a.href = url + `?redirect_to=${window.location.href}`
+ } else {
+ return
+ }
+ a.hidden = true;
+ a.click();
+ a.remove();
+ window.sessionStorage.setItem("authenticated_github_codespaces", "true")
+ }
+}
+doRedirect("%s")
+""" % Endpoint.AUTH_CODESPACE.get_url()
+
+
+def codespaces_port_forwarding_domain() -> str | None:
+ """Get the domain for port forwarding in Github Codespaces.
+
+ Returns:
+ The domain for port forwarding in Github Codespaces, or None if not running in Codespaces.
+ """
+ GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN = os.getenv(
+ "GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN"
+ )
+ return GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN
+
+
+def is_running_in_codespaces() -> bool:
+ """Check if the app is running in Github Codespaces.
+
+ Returns:
+ True if running in Github Codespaces, False otherwise.
+ """
+ return codespaces_port_forwarding_domain() is not None
+
+
+def codespaces_auto_redirect() -> list[Component]:
+ """Get the components for automatically redirecting back to the app after authenticating a codespace port forward.
+
+ Returns:
+ A list containing the conditional redirect component, or empty list.
+ """
+ if is_running_in_codespaces():
+ return [cond(has_connection_errors, Script.create(redirect_script))]
+ return []
+
+
+async def auth_codespace() -> HTMLResponse:
+ """Page automatically redirecting back to the app after authenticating a codespace port forward.
+
+ Returns:
+ An HTML response with an embedded script to redirect back to the app.
+ """
+ return HTMLResponse(
+ """
+
+
+ Reflex Github Codespace Forward Successfully Authenticated
+
+
+
+ Successfully Authenticated
+
+
+
+
+ """
+ % redirect_script
+ )
diff --git a/reflex/utils/compat.py b/reflex/utils/compat.py
index 0b5ad3ad8..e63492a6b 100644
--- a/reflex/utils/compat.py
+++ b/reflex/utils/compat.py
@@ -4,6 +4,30 @@ import contextlib
import sys
+async def windows_hot_reload_lifespan_hack():
+ """[REF-3164] A hack to fix hot reload on Windows.
+
+ Uvicorn has an issue stopping itself on Windows after detecting changes in
+ the filesystem.
+
+ This workaround repeatedly prints and flushes null characters to stderr,
+ which seems to allow the uvicorn server to exit when the CTRL-C signal is
+ sent from the reloader process.
+
+ Don't ask me why this works, I discovered it by accident - masenf.
+ """
+ import asyncio
+ import sys
+
+ try:
+ while True:
+ sys.stderr.write("\0")
+ sys.stderr.flush()
+ await asyncio.sleep(0.5)
+ except asyncio.CancelledError:
+ pass
+
+
@contextlib.contextmanager
def pydantic_v1_patch():
"""A context manager that patches the Pydantic module to mimic v1 behaviour.
@@ -11,6 +35,13 @@ def pydantic_v1_patch():
Yields:
None when the Pydantic module is patched.
"""
+ import pydantic
+
+ if pydantic.__version__.startswith("1."):
+ # pydantic v1 is already installed
+ yield
+ return
+
patched_modules = [
"pydantic",
"pydantic.fields",
@@ -41,3 +72,19 @@ def pydantic_v1_patch():
with pydantic_v1_patch():
import sqlmodel as sqlmodel
+
+
+def sqlmodel_field_has_primary_key(field) -> bool:
+ """Determines if a field is a priamary.
+
+ Args:
+ field: a rx.model field
+
+ Returns:
+ If field is a primary key (Bool)
+ """
+ if getattr(field.field_info, "primary_key", None) is True:
+ return True
+ if getattr(field.field_info, "sa_column", None) is None:
+ return False
+ return bool(getattr(field.field_info.sa_column, "primary_key", None))
diff --git a/reflex/utils/console.py b/reflex/utils/console.py
index a54103064..20c699e20 100644
--- a/reflex/utils/console.py
+++ b/reflex/utils/console.py
@@ -17,6 +17,9 @@ _LOG_LEVEL = LogLevel.INFO
# Deprecated features who's warning has been printed.
_EMITTED_DEPRECATION_WARNINGS = set()
+# Info messages which have been printed.
+_EMITTED_INFO = set()
+
def set_log_level(log_level: LogLevel):
"""Set the log level.
@@ -55,21 +58,27 @@ def debug(msg: str, **kwargs):
kwargs: Keyword arguments to pass to the print function.
"""
if is_debug():
- msg_ = f"[blue]Debug: {msg}[/blue]"
+ msg_ = f"[purple]Debug: {msg}[/purple]"
if progress := kwargs.pop("progress", None):
progress.console.print(msg_, **kwargs)
else:
print(msg_, **kwargs)
-def info(msg: str, **kwargs):
+def info(msg: str, dedupe: bool = False, **kwargs):
"""Print an info message.
Args:
msg: The info message.
+ dedupe: If True, suppress multiple console logs of info message.
kwargs: Keyword arguments to pass to the print function.
"""
if _LOG_LEVEL <= LogLevel.INFO:
+ if dedupe:
+ if msg in _EMITTED_INFO:
+ return
+ else:
+ _EMITTED_INFO.add(msg)
print(f"[cyan]Info: {msg}[/cyan]", **kwargs)
diff --git a/reflex/utils/exceptions.py b/reflex/utils/exceptions.py
index aabaaef14..661f29095 100644
--- a/reflex/utils/exceptions.py
+++ b/reflex/utils/exceptions.py
@@ -5,6 +5,14 @@ class ReflexError(Exception):
"""Base exception for all Reflex exceptions."""
+class ConfigError(ReflexError):
+ """Custom exception for config related errors."""
+
+
+class InvalidStateManagerMode(ReflexError, ValueError):
+ """Raised when an invalid state manager mode is provided."""
+
+
class ReflexRuntimeError(ReflexError, RuntimeError):
"""Custom RuntimeError for Reflex."""
@@ -61,6 +69,10 @@ class VarOperationTypeError(ReflexError, TypeError):
"""Custom TypeError for when unsupported operations are performed on vars."""
+class VarDependencyError(ReflexError, ValueError):
+ """Custom ValueError for when a var depends on a non-existent var."""
+
+
class InvalidStylePropError(ReflexError, TypeError):
"""Custom Type Error when style props have invalid values."""
@@ -75,3 +87,67 @@ class LockExpiredError(ReflexError):
class MatchTypeError(ReflexError, TypeError):
"""Raised when the return types of match cases are different."""
+
+
+class EventHandlerArgMismatch(ReflexError, TypeError):
+ """Raised when the number of args accepted by an EventHandler differs from that provided by the event trigger."""
+
+
+class EventHandlerArgTypeMismatch(ReflexError, TypeError):
+ """Raised when the annotations of args accepted by an EventHandler differs from the spec of the event trigger."""
+
+
+class EventFnArgMismatch(ReflexError, TypeError):
+ """Raised when the number of args accepted by a lambda differs from that provided by the event trigger."""
+
+
+class DynamicRouteArgShadowsStateVar(ReflexError, NameError):
+ """Raised when a dynamic route arg shadows a state var."""
+
+
+class ComputedVarShadowsStateVar(ReflexError, NameError):
+ """Raised when a computed var shadows a state var."""
+
+
+class ComputedVarShadowsBaseVars(ReflexError, NameError):
+ """Raised when a computed var shadows a base var."""
+
+
+class EventHandlerShadowsBuiltInStateMethod(ReflexError, NameError):
+ """Raised when an event handler shadows a built-in state method."""
+
+
+class GeneratedCodeHasNoFunctionDefs(ReflexError):
+ """Raised when refactored code generated with flexgen has no functions defined."""
+
+
+class PrimitiveUnserializableToJSON(ReflexError, ValueError):
+ """Raised when a primitive type is unserializable to JSON. Usually with NaN and Infinity."""
+
+
+class InvalidLifespanTaskType(ReflexError, TypeError):
+ """Raised when an invalid task type is registered as a lifespan task."""
+
+
+class DynamicComponentMissingLibrary(ReflexError, ValueError):
+ """Raised when a dynamic component is missing a library."""
+
+
+class SetUndefinedStateVarError(ReflexError, AttributeError):
+ """Raised when setting the value of a var without first declaring it."""
+
+
+class StateSchemaMismatchError(ReflexError, TypeError):
+ """Raised when the serialized schema of a state class does not match the current schema."""
+
+
+class EnvironmentVarValueError(ReflexError, ValueError):
+ """Raised when an environment variable is set to an invalid value."""
+
+
+class DynamicComponentInvalidSignature(ReflexError, TypeError):
+ """Raised when a dynamic component has an invalid signature."""
+
+
+class InvalidPropValueError(ReflexError):
+ """Raised when a prop value is invalid."""
diff --git a/reflex/utils/exec.py b/reflex/utils/exec.py
index e4aefb8f1..bdc9be4ae 100644
--- a/reflex/utils/exec.py
+++ b/reflex/utils/exec.py
@@ -15,24 +15,15 @@ from urllib.parse import urljoin
import psutil
from reflex import constants
-from reflex.config import get_config
+from reflex.config import environment, get_config
+from reflex.constants.base import LogLevel
from reflex.utils import console, path_ops
-from reflex.utils.watch import AssetFolderWatch
+from reflex.utils.prerequisites import get_web_dir
# For uvicorn windows bug fix (#2335)
frontend_process = None
-def start_watching_assets_folder(root):
- """Start watching assets folder.
-
- Args:
- root: root path of the project.
- """
- asset_watch = AssetFolderWatch(root)
- asset_watch.start()
-
-
def detect_package_change(json_file_path: str) -> str:
"""Calculates the SHA-256 hash of a JSON file and returns it as a hexadecimal string.
@@ -70,6 +61,13 @@ def kill(proc_pid: int):
process.kill()
+def notify_backend():
+ """Output a string notifying where the backend is running."""
+ console.print(
+ f"Backend running at: [bold green]http://0.0.0.0:{get_config().backend_port}[/bold green]"
+ )
+
+
# run_process_and_launch_url is assumed to be used
# only to launch the frontend
# If this is not the case, might have to change the logic
@@ -82,8 +80,8 @@ def run_process_and_launch_url(run_command: list[str], backend_present=True):
"""
from reflex.utils import processes
- json_file_path = os.path.join(constants.Dirs.WEB, "package.json")
- last_hash = detect_package_change(json_file_path)
+ json_file_path = get_web_dir() / constants.PackageJson.PATH
+ last_hash = detect_package_change(str(json_file_path))
process = None
first_run = True
@@ -94,7 +92,7 @@ def run_process_and_launch_url(run_command: list[str], backend_present=True):
kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore
process = processes.new_process(
run_command,
- cwd=constants.Dirs.WEB,
+ cwd=get_web_dir(),
shell=constants.IS_WINDOWS,
**kwargs,
)
@@ -108,12 +106,25 @@ def run_process_and_launch_url(run_command: list[str], backend_present=True):
url = match.group(1)
if get_config().frontend_path != "":
url = urljoin(url, get_config().frontend_path)
- console.print(f"App running at: [bold green]{url}")
+
+ console.print(
+ f"App running at: [bold green]{url}[/bold green]{' (Frontend-only mode)' if not backend_present else ''}"
+ )
+ if backend_present:
+ notify_backend()
first_run = False
else:
console.print("New packages detected: Updating app...")
else:
- new_hash = detect_package_change(json_file_path)
+ if any(
+ [x in line for x in ("bin executable does not exist on disk",)]
+ ):
+ console.error(
+ "Try setting `REFLEX_USE_NPM=1` and re-running `reflex init` and `reflex run` to use npm instead of bun:\n"
+ "`REFLEX_USE_NPM=1 reflex init`\n"
+ "`REFLEX_USE_NPM=1 reflex run`"
+ )
+ new_hash = detect_package_change(str(json_file_path))
if new_hash != last_hash:
last_hash = new_hash
kill(process.pid)
@@ -133,8 +144,6 @@ def run_frontend(root: Path, port: str, backend_present=True):
"""
from reflex.utils import prerequisites
- # Start watching asset folder.
- start_watching_assets_folder(root)
# validate dependencies before run
prerequisites.validate_frontend_dependencies(init=False)
@@ -169,13 +178,69 @@ def run_frontend_prod(root: Path, port: str, backend_present=True):
)
+def should_use_granian():
+ """Whether to use Granian for backend.
+
+ Returns:
+ True if Granian should be used.
+ """
+ return environment.REFLEX_USE_GRANIAN
+
+
+def get_app_module():
+ """Get the app module for the backend.
+
+ Returns:
+ The app module for the backend.
+ """
+ return f"reflex.app_module_for_backend:{constants.CompileVars.APP}"
+
+
+def get_granian_target():
+ """Get the Granian target for the backend.
+
+ Returns:
+ The Granian target for the backend.
+ """
+ import reflex
+
+ app_module_path = Path(reflex.__file__).parent / "app_module_for_backend.py"
+
+ return f"{str(app_module_path)}:{constants.CompileVars.APP}.{constants.CompileVars.API}"
+
+
def run_backend(
host: str,
port: int,
loglevel: constants.LogLevel = constants.LogLevel.ERROR,
+ frontend_present: bool = False,
):
"""Run the backend.
+ Args:
+ host: The app host
+ port: The app port
+ loglevel: The log level.
+ frontend_present: Whether the frontend is present.
+ """
+ web_dir = get_web_dir()
+ # Create a .nocompile file to skip compile for backend.
+ if web_dir.exists():
+ (web_dir / constants.NOCOMPILE_FILE).touch()
+
+ if not frontend_present:
+ notify_backend()
+
+ # Run the backend in development mode.
+ if should_use_granian():
+ run_granian_backend(host, port, loglevel)
+ else:
+ run_uvicorn_backend(host, port, loglevel)
+
+
+def run_uvicorn_backend(host, port, loglevel: LogLevel):
+ """Run the backend in development mode using Uvicorn.
+
Args:
host: The app host
port: The app port
@@ -183,23 +248,55 @@ def run_backend(
"""
import uvicorn
- config = get_config()
- app_module = f"reflex.app_module_for_backend:{constants.CompileVars.APP}"
-
- # Create a .nocompile file to skip compile for backend.
- if os.path.exists(constants.Dirs.WEB):
- with open(constants.NOCOMPILE_FILE, "w"):
- pass
-
- # Run the backend in development mode.
uvicorn.run(
- app=f"{app_module}.{constants.CompileVars.API}",
+ app=f"{get_app_module()}.{constants.CompileVars.API}",
host=host,
port=port,
log_level=loglevel.value,
reload=True,
- reload_dirs=[config.app_name],
- reload_excludes=[constants.Dirs.WEB],
+ reload_dirs=[get_config().app_name],
+ )
+
+
+def run_granian_backend(host, port, loglevel: LogLevel):
+ """Run the backend in development mode using Granian.
+
+ Args:
+ host: The app host
+ port: The app port
+ loglevel: The log level.
+ """
+ console.debug("Using Granian for backend")
+ try:
+ from granian import Granian # type: ignore
+ from granian.constants import Interfaces # type: ignore
+ from granian.log import LogLevels # type: ignore
+
+ Granian(
+ target=get_granian_target(),
+ address=host,
+ port=port,
+ interface=Interfaces.ASGI,
+ log_level=LogLevels(loglevel.value),
+ reload=True,
+ reload_paths=[Path(get_config().app_name)],
+ reload_ignore_dirs=[".web"],
+ ).serve()
+ except ImportError:
+ console.error(
+ 'InstallError: REFLEX_USE_GRANIAN is set but `granian` is not installed. (run `pip install "granian[reload]>=1.6.0"`)'
+ )
+ os._exit(1)
+
+
+def _get_backend_workers():
+ from reflex.utils import processes
+
+ config = get_config()
+ return (
+ processes.get_num_workers()
+ if not config.gunicorn_workers
+ else config.gunicorn_workers
)
@@ -207,9 +304,28 @@ def run_backend_prod(
host: str,
port: int,
loglevel: constants.LogLevel = constants.LogLevel.ERROR,
+ frontend_present: bool = False,
):
"""Run the backend.
+ Args:
+ host: The app host
+ port: The app port
+ loglevel: The log level.
+ frontend_present: Whether the frontend is present.
+ """
+ if not frontend_present:
+ notify_backend()
+
+ if should_use_granian():
+ run_granian_backend_prod(host, port, loglevel)
+ else:
+ run_uvicorn_backend_prod(host, port, loglevel)
+
+
+def run_uvicorn_backend_prod(host, port, loglevel):
+ """Run the backend in production mode using Uvicorn.
+
Args:
host: The app host
port: The app port
@@ -217,11 +333,12 @@ def run_backend_prod(
"""
from reflex.utils import processes
- num_workers = processes.get_num_workers()
config = get_config()
- RUN_BACKEND_PROD = f"gunicorn --worker-class {config.gunicorn_worker_class} --preload --timeout {config.timeout} --log-level critical".split()
- RUN_BACKEND_PROD_WINDOWS = f"uvicorn --timeout-keep-alive {config.timeout}".split()
- app_module = f"reflex.app_module_for_backend:{constants.CompileVars.APP}"
+
+ app_module = get_app_module()
+
+ RUN_BACKEND_PROD = f"gunicorn --worker-class {config.gunicorn_worker_class} --max-requests {config.gunicorn_max_requests} --max-requests-jitter {config.gunicorn_max_requests_jitter} --preload --timeout {config.timeout} --log-level critical".split()
+ RUN_BACKEND_PROD_WINDOWS = f"uvicorn --limit-max-requests {config.gunicorn_max_requests} --timeout-keep-alive {config.timeout}".split()
command = (
[
*RUN_BACKEND_PROD_WINDOWS,
@@ -237,7 +354,7 @@ def run_backend_prod(
"--bind",
f"{host}:{port}",
"--threads",
- str(num_workers),
+ str(_get_backend_workers()),
f"{app_module}()",
]
)
@@ -246,7 +363,7 @@ def run_backend_prod(
"--log-level",
loglevel.value,
"--workers",
- str(num_workers),
+ str(_get_backend_workers()),
]
processes.new_process(
command,
@@ -256,6 +373,47 @@ def run_backend_prod(
)
+def run_granian_backend_prod(host, port, loglevel):
+ """Run the backend in production mode using Granian.
+
+ Args:
+ host: The app host
+ port: The app port
+ loglevel: The log level.
+ """
+ from reflex.utils import processes
+
+ try:
+ from granian.constants import Interfaces # type: ignore
+
+ command = [
+ "granian",
+ "--workers",
+ str(_get_backend_workers()),
+ "--log-level",
+ "critical",
+ "--host",
+ host,
+ "--port",
+ str(port),
+ "--interface",
+ str(Interfaces.ASGI),
+ get_granian_target(),
+ ]
+ processes.new_process(
+ command,
+ run=True,
+ show_logs=True,
+ env={
+ constants.SKIP_COMPILE_ENV_VAR: "yes"
+ }, # skip compile for prod backend
+ )
+ except ImportError:
+ console.error(
+ 'InstallError: REFLEX_USE_GRANIAN is set but `granian` is not installed. (run `pip install "granian[reload]>=1.6.0"`)'
+ )
+
+
def output_system_info():
"""Show system information if the loglevel is in DEBUG."""
if console._LOG_LEVEL > constants.LogLevel.DEBUG:
@@ -338,6 +496,24 @@ def is_prod_mode() -> bool:
return current_mode == constants.Env.PROD.value
+def is_frontend_only() -> bool:
+ """Check if the app is running in frontend-only mode.
+
+ Returns:
+ True if the app is running in frontend-only mode.
+ """
+ return os.environ.get(constants.ENV_FRONTEND_ONLY_ENV_VAR, "").lower() == "true"
+
+
+def is_backend_only() -> bool:
+ """Check if the app is running in backend-only mode.
+
+ Returns:
+ True if the app is running in backend-only mode.
+ """
+ return os.environ.get(constants.ENV_BACKEND_ONLY_ENV_VAR, "").lower() == "true"
+
+
def should_skip_compile() -> bool:
"""Whether the app should skip compile.
diff --git a/reflex/utils/export.py b/reflex/utils/export.py
index 3116f4859..31ac0d0b5 100644
--- a/reflex/utils/export.py
+++ b/reflex/utils/export.py
@@ -1,4 +1,5 @@
"""Export utilities."""
+
import os
from pathlib import Path
from typing import Optional
@@ -55,15 +56,18 @@ def export(
# Set up .web directory and install frontend dependencies.
build.setup_frontend(Path.cwd())
- # Export the app.
- build.export(
- backend=backend,
- frontend=frontend,
- zip=zipping,
- zip_dest_dir=zip_dest_dir,
- deploy_url=config.deploy_url,
- upload_db_file=upload_db_file,
- )
+ # Build the static app.
+ if frontend:
+ build.build(deploy_url=config.deploy_url, for_export=True)
+
+ # Zip up the app.
+ if zipping:
+ build.zip_app(
+ frontend=frontend,
+ backend=backend,
+ zip_dest_dir=zip_dest_dir,
+ upload_db_file=upload_db_file,
+ )
# Post a telemetry event.
telemetry.send("export")
diff --git a/reflex/utils/format.py b/reflex/utils/format.py
index 70f6b5b25..a914a585c 100644
--- a/reflex/utils/format.py
+++ b/reflex/utils/format.py
@@ -6,16 +6,15 @@ import inspect
import json
import os
import re
-from typing import TYPE_CHECKING, Any, List, Optional, Union
+from typing import TYPE_CHECKING, Any, Callable, List, Optional, Union
from reflex import constants
-from reflex.utils import exceptions, serializers, types
-from reflex.utils.serializers import serialize
-from reflex.vars import BaseVar, Var
+from reflex.utils import exceptions
+from reflex.utils.console import deprecate
if TYPE_CHECKING:
from reflex.components.component import ComponentStyle
- from reflex.event import EventChain, EventHandler, EventSpec
+ from reflex.event import ArgsSpec, EventChain, EventHandler, EventSpec
WRAP_MAP = {
"{": "}",
@@ -198,8 +197,16 @@ def make_default_page_title(app_name: str, route: str) -> str:
Returns:
The default page title.
"""
- title = constants.DefaultPage.TITLE.format(app_name, route)
- return to_title_case(title, " ")
+ route_parts = [
+ part
+ for part in route.split("/")
+ if part and not (part.startswith("[") and part.endswith("]"))
+ ]
+
+ title = constants.DefaultPage.TITLE.format(
+ app_name, route_parts[-1] if route_parts else constants.PageNames.INDEX_ROUTE
+ )
+ return to_title_case(title)
def _escape_js_string(string: str) -> str:
@@ -211,10 +218,31 @@ def _escape_js_string(string: str) -> str:
Returns:
The escaped string.
"""
- # Escape backticks.
- string = string.replace(r"\`", "`")
- string = string.replace("`", r"\`")
- return 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:
@@ -243,32 +271,6 @@ def format_string(string: str) -> str:
return _wrap_js_string(_escape_js_string(string))
-def format_f_string_prop(prop: BaseVar) -> str:
- """Format the string in a given prop as an f-string.
-
- Args:
- prop: The prop to format.
-
- Returns:
- The formatted string.
- """
- s = prop._var_full_name
- var_data = prop._var_data
- interps = var_data.interpolations if var_data else []
- parts: List[str] = []
-
- if interps:
- for i, (start, end) in enumerate(interps):
- prev_end = interps[i - 1][1] if i > 0 else 0
- parts.append(_escape_js_string(s[prev_end:start]))
- parts.append(s[start:end])
- parts.append(_escape_js_string(s[interps[-1][1] :]))
- else:
- parts.append(_escape_js_string(s))
-
- return _wrap_js_string("".join(parts))
-
-
def format_var(var: Var) -> str:
"""Format the given Var as a javascript value.
@@ -278,13 +280,7 @@ def format_var(var: Var) -> str:
Returns:
The formatted Var.
"""
- if not var._var_is_local or var._var_is_string:
- return str(var)
- if types._issubclass(var._var_type, str):
- return format_string(var._var_full_name)
- if is_wrapped(var._var_full_name, "{"):
- return var._var_full_name
- return json_dumps(var._var_full_name)
+ return str(var)
def format_route(route: str, format_case=True) -> str:
@@ -309,46 +305,11 @@ def format_route(route: str, format_case=True) -> str:
return route
-def format_cond(
+def format_match(
cond: str | Var,
- true_value: str | Var,
- false_value: str | Var = '""',
- is_prop=False,
+ match_cases: List[List[Var]],
+ default: Var,
) -> str:
- """Format a conditional expression.
-
- Args:
- cond: The cond.
- true_value: The value to return if the cond is true.
- false_value: The value to return if the cond is false.
- is_prop: Whether the cond is a prop
-
- Returns:
- The formatted conditional expression.
- """
- # Use Python truthiness.
- cond = f"isTrue({cond})"
-
- def create_var(cond_part):
- return Var.create_safe(cond_part, _var_is_string=isinstance(cond_part, str))
-
- # Format prop conds.
- if is_prop:
- true_value = create_var(true_value)
- prop1 = true_value._replace(
- _var_is_local=True,
- )
-
- false_value = create_var(false_value)
- prop2 = false_value._replace(_var_is_local=True)
- # unwrap '{}' to avoid f-string semantics for Var
- return f"{cond} ? {prop1._var_name_unwrapped} : {prop2._var_name_unwrapped}"
-
- # Format component conds.
- return wrap(f"{cond} ? {true_value} : {false_value}", "{")
-
-
-def format_match(cond: str | Var, match_cases: List[BaseVar], default: Var) -> str:
"""Format a match expression whose return type is a Var.
Args:
@@ -367,17 +328,12 @@ def format_match(cond: str | Var, match_cases: List[BaseVar], default: Var) -> s
return_value = case[-1]
case_conditions = " ".join(
- [
- f"case JSON.stringify({condition._var_name_unwrapped}):"
- for condition in conditions
- ]
- )
- case_code = (
- f"{case_conditions} return ({return_value._var_name_unwrapped}); break;"
+ [f"case JSON.stringify({str(condition)}):" for condition in conditions]
)
+ case_code = f"{case_conditions} return ({str(return_value)}); break;"
switch_code += case_code
- switch_code += f"default: return ({default._var_name_unwrapped}); break;"
+ switch_code += f"default: return ({str(default)}); break;"
switch_code += "};})()"
return switch_code
@@ -397,35 +353,21 @@ def format_prop(
Raises:
exceptions.InvalidStylePropError: If the style prop value is not a valid type.
TypeError: If the prop is not valid.
+ ValueError: If the prop is not a string.
"""
# import here to avoid circular import.
from reflex.event import EventChain
+ from reflex.utils import serializers
+ from reflex.vars import Var
try:
# Handle var props.
if isinstance(prop, Var):
- if not prop._var_is_local or prop._var_is_string:
- return str(prop)
- if isinstance(prop, BaseVar) and types._issubclass(prop._var_type, str):
- if prop._var_data and prop._var_data.interpolations:
- return format_f_string_prop(prop)
- return format_string(prop._var_full_name)
- prop = prop._var_full_name
+ return str(prop)
# Handle event props.
- elif isinstance(prop, EventChain):
- sig = inspect.signature(prop.args_spec) # type: ignore
- if sig.parameters:
- arg_def = ",".join(f"_{p}" for p in sig.parameters)
- arg_def = f"({arg_def})"
- else:
- # add a default argument for addEvents if none were specified in prop.args_spec
- # used to trigger the preventDefault() on the event.
- arg_def = "(_e)"
-
- chain = ",".join([format_event(event) for event in prop.events])
- event = f"addEvents([{chain}], {arg_def}, {json_dumps(prop.event_actions)})"
- prop = f"{arg_def} => {event}"
+ if isinstance(prop, EventChain):
+ return str(Var.create(prop))
# Handle other types.
elif isinstance(prop, str):
@@ -446,7 +388,8 @@ def format_prop(
raise TypeError(f"Could not format prop: {prop} of type {type(prop)}") from e
# Wrap the variable in braces.
- assert isinstance(prop, str), "The prop must be a string."
+ if not isinstance(prop, str):
+ raise ValueError(f"Invalid prop: {prop}. Expected a string.")
return wrap(prop, "{", check_first=False)
@@ -461,11 +404,15 @@ def format_props(*single_props, **key_value_props) -> list[str]:
The formatted props list.
"""
# Format all the props.
+ from reflex.vars.base import LiteralVar, Var
+
return [
- f"{name}={format_prop(prop)}"
+ (
+ f"{name}={{{format_prop(prop if isinstance(prop, Var) else LiteralVar.create(prop))}}}"
+ )
for name, prop in sorted(key_value_props.items())
if prop is not None
- ] + [str(prop) for prop in single_props]
+ ] + [(f"{str(LiteralVar.create(prop))}") for prop in single_props]
def get_event_handler_parts(handler: EventHandler) -> tuple[str, str]:
@@ -480,13 +427,13 @@ def get_event_handler_parts(handler: EventHandler) -> tuple[str, str]:
# Get the class that defines the event handler.
parts = handler.fn.__qualname__.split(".")
- # If there's no enclosing class, just return the function name.
- if len(parts) == 1:
- return ("", parts[-1])
-
# Get the state full name
state_full_name = handler.state_full_name
+ # If there's no enclosing class, just return the function name.
+ if not state_full_name:
+ return ("", parts[-1])
+
# Get the function name
name = parts[-1]
@@ -526,14 +473,14 @@ def format_event(event_spec: EventSpec) -> str:
[
":".join(
(
- name._var_name,
+ name._js_expr,
(
wrap(
- json.dumps(val._var_name).strip('"').replace("`", "\\`"),
+ json.dumps(val._js_expr).strip('"').replace("`", "\\`"),
"`",
)
if val._var_is_string
- else val._var_full_name
+ else str(val)
),
)
)
@@ -550,44 +497,116 @@ def format_event(event_spec: EventSpec) -> str:
return f"Event({', '.join(event_args)})"
+if TYPE_CHECKING:
+ from reflex.vars import Var
+
+
def format_event_chain(
event_chain: EventChain | Var[EventChain],
event_arg: Var | None = None,
) -> str:
- """Format an event chain as a javascript invocation.
+ """DEPRECATED: format an event chain as a javascript invocation.
+
+ Use str(rx.Var.create(event_chain)) instead.
Args:
- event_chain: The event chain to queue on the frontend.
- event_arg: The browser-native event (only used to preventDefault).
+ event_chain: The event chain to format.
+ event_arg: this argument is ignored.
Returns:
Compiled javascript code to queue the given event chain on the frontend.
+ """
+ deprecate(
+ feature_name="format_event_chain",
+ reason="Use str(rx.Var.create(event_chain)) instead",
+ deprecation_version="0.6.0",
+ removal_version="0.7.0",
+ )
+
+ from reflex.vars import Var
+ from reflex.vars.function import ArgsFunctionOperation
+
+ result = Var.create(event_chain)
+ if isinstance(result, ArgsFunctionOperation):
+ result = result._return_expr
+ return str(result)
+
+
+def format_queue_events(
+ events: (
+ EventSpec
+ | EventHandler
+ | Callable
+ | List[EventSpec | EventHandler | Callable]
+ | None
+ ) = None,
+ args_spec: Optional[ArgsSpec] = None,
+) -> Var[EventChain]:
+ """Format a list of event handler / event spec as a javascript callback.
+
+ The resulting code can be passed to interfaces that expect a callback
+ function and when triggered it will directly call queueEvents.
+
+ It is intended to be executed in the rx.call_script context, where some
+ existing API needs a callback to trigger a backend event handler.
+
+ Args:
+ events: The events to queue.
+ args_spec: The argument spec for the callback.
+
+ Returns:
+ The compiled javascript callback to queue the given events on the frontend.
Raises:
- ValueError: When the given event chain is not a valid event chain.
+ ValueError: If a lambda function is given which returns a Var.
"""
- if isinstance(event_chain, Var):
- from reflex.event import EventChain
-
- if event_chain._var_type is not EventChain:
- raise ValueError(f"Invalid event chain: {event_chain}")
- return "".join(
- [
- "(() => {",
- format_var(event_chain),
- f"; preventDefault({format_var(event_arg)})" if event_arg else "",
- "})()",
- ]
- )
-
- chain = ",".join([format_event(event) for event in event_chain.events])
- return "".join(
- [
- f"addEvents([{chain}]",
- f", {format_var(event_arg)}" if event_arg else "",
- ")",
- ]
+ from reflex.event import (
+ EventChain,
+ EventHandler,
+ EventSpec,
+ call_event_fn,
+ call_event_handler,
)
+ from reflex.vars import FunctionVar, Var
+
+ if not events:
+ return Var("(() => null)").to(FunctionVar, EventChain) # type: ignore
+
+ # If no spec is provided, the function will take no arguments.
+ def _default_args_spec():
+ return []
+
+ # Construct the arguments that the function accepts.
+ sig = inspect.signature(args_spec or _default_args_spec) # type: ignore
+ if sig.parameters:
+ arg_def = ",".join(f"_{p}" for p in sig.parameters)
+ arg_def = f"({arg_def})"
+ else:
+ arg_def = "()"
+
+ payloads = []
+ if not isinstance(events, list):
+ events = [events]
+
+ # Process each event/spec/lambda (similar to Component._create_event_chain).
+ for spec in events:
+ specs: list[EventSpec] = []
+ if isinstance(spec, (EventHandler, EventSpec)):
+ specs = [call_event_handler(spec, args_spec or _default_args_spec)]
+ elif isinstance(spec, type(lambda: None)):
+ specs = call_event_fn(spec, args_spec or _default_args_spec) # type: ignore
+ if isinstance(specs, Var):
+ raise ValueError(
+ f"Invalid event spec: {specs}. Expected a list of EventSpecs."
+ )
+ payloads.extend(format_event(s) for s in specs)
+
+ # Return the final code snippet, expecting queueEvents, processEvent, and socket to be in scope.
+ # Typically this snippet will _only_ run from within an rx.call_script eval context.
+ return Var(
+ f"{arg_def} => {{queueEvents([{','.join(payloads)}], {constants.CompileVars.SOCKET}); "
+ f"processEvent({constants.CompileVars.SOCKET})}}",
+ ).to(FunctionVar, EventChain) # type: ignore
def format_query_params(router_data: dict[str, Any]) -> dict[str, str]:
@@ -603,46 +622,6 @@ def format_query_params(router_data: dict[str, Any]) -> dict[str, str]:
return {k.replace("-", "_"): v for k, v in params.items()}
-def format_state(value: Any, key: Optional[str] = None) -> Any:
- """Recursively format values in the given state.
-
- Args:
- value: The state to format.
- key: The key associated with the value (optional).
-
- Returns:
- The formatted state.
-
- Raises:
- TypeError: If the given value is not a valid state.
- """
- # Handle dicts.
- if isinstance(value, dict):
- return {k: format_state(v, k) for k, v in value.items()}
-
- # Handle lists, sets, typles.
- if isinstance(value, types.StateIterBases):
- return [format_state(v) for v in value]
-
- # Return state vars as is.
- if isinstance(value, types.StateBases):
- return value
-
- # Serialize the value.
- serialized = serialize(value)
- if serialized is not None:
- return serialized
-
- if key is None:
- raise TypeError(
- f"No JSON serializer found for var {value} of type {type(value)}."
- )
- else:
- raise TypeError(
- f"No JSON serializer found for State Var '{key}' of value {value} of type {type(value)}."
- )
-
-
def format_state_name(state_name: str) -> str:
"""Format a state name, replacing dots with double underscore.
@@ -672,41 +651,6 @@ def format_ref(ref: str) -> str:
return f"ref_{clean_ref}"
-def format_array_ref(refs: str, idx: Var | None) -> str:
- """Format a ref accessed by array.
-
- Args:
- refs : The ref array to access.
- idx : The index of the ref in the array.
-
- Returns:
- The formatted ref.
- """
- clean_ref = re.sub(r"[^\w]+", "_", refs)
- if idx is not None:
- idx._var_is_local = True
- return f"refs_{clean_ref}[{idx}]"
- return f"refs_{clean_ref}"
-
-
-def format_breadcrumbs(route: str) -> list[tuple[str, str]]:
- """Take a route and return a list of tuple for use in breadcrumb.
-
- Args:
- route: The route to transform.
-
- Returns:
- list[tuple[str, str]]: the list of tuples for the breadcrumb.
- """
- route_parts = route.lstrip("/").split("/")
-
- # create and return breadcrumbs
- return [
- (part, "/".join(["", *route_parts[: i + 1]]))
- for i, part in enumerate(route_parts)
- ]
-
-
def format_library_name(library_fullname: str):
"""Format the name of a library.
@@ -716,6 +660,8 @@ def format_library_name(library_fullname: str):
Returns:
The name without the @version if it was part of the name
"""
+ if library_fullname.startswith("https://"):
+ return library_fullname
lib, at, version = library_fullname.rpartition("@")
if not lib:
lib = at + version
@@ -732,43 +678,9 @@ def json_dumps(obj: Any) -> str:
Returns:
A string
"""
- return json.dumps(obj, ensure_ascii=False, default=serialize)
+ from reflex.utils import serializers
-
-def unwrap_vars(value: str) -> str:
- """Unwrap var values from a JSON string.
-
- For example, "{var}" will be unwrapped to "var".
-
- Args:
- value: The JSON string to unwrap.
-
- Returns:
- The unwrapped JSON string.
- """
-
- def unescape_double_quotes_in_var(m: re.Match) -> str:
- prefix = m.group(1) or ""
- # Since the outer quotes are removed, the inner escaped quotes must be unescaped.
- return prefix + re.sub('\\\\"', '"', m.group(2))
-
- # This substitution is necessary to unwrap var values.
- return (
- re.sub(
- pattern=r"""
- (?.*?)? # Optional encoded VarData (non-greedy)
- {(.*?)} # extract the value between curly braces (non-greedy)
- " # match must end with an unescaped double quote
- """,
- repl=unescape_double_quotes_in_var,
- string=value,
- flags=re.VERBOSE,
- )
- .replace('"`', "`")
- .replace('`"', "`")
- )
+ return json.dumps(obj, ensure_ascii=False, default=serializers.serialize)
def collect_form_dict_names(form_dict: dict[str, Any]) -> dict[str, Any]:
@@ -793,6 +705,23 @@ def collect_form_dict_names(form_dict: dict[str, Any]) -> dict[str, Any]:
return collapsed
+def format_array_ref(refs: str, idx: Var | None) -> str:
+ """Format a ref accessed by array.
+
+ Args:
+ refs : The ref array to access.
+ idx : The index of the ref in the array.
+
+ Returns:
+ The formatted ref.
+ """
+ clean_ref = re.sub(r"[^\w]+", "_", refs)
+ if idx is not None:
+ # idx._var_is_local = True
+ return f"refs_{clean_ref}[{str(idx)}]"
+ return f"refs_{clean_ref}"
+
+
def format_data_editor_column(col: str | dict):
"""Format a given column into the proper format.
@@ -805,6 +734,8 @@ def format_data_editor_column(col: str | dict):
Returns:
The formatted column.
"""
+ from reflex.vars import Var
+
if isinstance(col, str):
return {"title": col, "id": col.lower(), "type": "str"}
@@ -817,7 +748,7 @@ def format_data_editor_column(col: str | dict):
col["overlayIcon"] = None
return col
- if isinstance(col, BaseVar):
+ if isinstance(col, Var):
return col
raise ValueError(
@@ -834,4 +765,9 @@ def format_data_editor_cell(cell: Any):
Returns:
The formatted cell.
"""
- return {"kind": Var.create(value="GridCellKind.Text"), "data": cell}
+ from reflex.vars.base import Var
+
+ return {
+ "kind": Var(_js_expr="GridCellKind.Text"),
+ "data": cell,
+ }
diff --git a/reflex/utils/imports.py b/reflex/utils/imports.py
index 263de1e3d..bd422ecc0 100644
--- a/reflex/utils/imports.py
+++ b/reflex/utils/imports.py
@@ -2,13 +2,14 @@
from __future__ import annotations
+import dataclasses
from collections import defaultdict
-from typing import Dict, List, Optional
-
-from reflex.base import Base
+from typing import DefaultDict, Dict, List, Optional, Tuple, Union
-def merge_imports(*imports) -> ImportDict:
+def merge_imports(
+ *imports: ImportDict | ParsedImportDict | ImmutableParsedImportDict,
+) -> ParsedImportDict:
"""Merge multiple import dicts together.
Args:
@@ -17,14 +18,58 @@ def merge_imports(*imports) -> ImportDict:
Returns:
The merged import dicts.
"""
- all_imports = defaultdict(list)
+ all_imports: DefaultDict[str, List[ImportVar]] = defaultdict(list)
for import_dict in imports:
- for lib, fields in import_dict.items():
- all_imports[lib].extend(fields)
+ for lib, fields in (
+ import_dict if isinstance(import_dict, tuple) else import_dict.items()
+ ):
+ # If the lib is an absolute path, we need to prefix it with a $
+ lib = (
+ "$" + lib
+ if lib.startswith(("/utils/", "/components/", "/styles/", "/public/"))
+ else lib
+ )
+ if isinstance(fields, (list, tuple, set)):
+ all_imports[lib].extend(
+ (
+ ImportVar(field) if isinstance(field, str) else field
+ for field in fields
+ )
+ )
+ else:
+ all_imports[lib].append(
+ ImportVar(fields) if isinstance(fields, str) else fields
+ )
return all_imports
-def collapse_imports(imports: ImportDict) -> ImportDict:
+def parse_imports(imports: ImportDict | ParsedImportDict) -> ParsedImportDict:
+ """Parse the import dict into a standard format.
+
+ Args:
+ imports: The import dict to parse.
+
+ Returns:
+ The parsed import dict.
+ """
+
+ def _make_list(value: ImportTypes) -> list[str | ImportVar] | list[ImportVar]:
+ if isinstance(value, (str, ImportVar)):
+ return [value]
+ return value
+
+ return {
+ package: [
+ ImportVar(tag=tag) if isinstance(tag, str) else tag
+ for tag in _make_list(maybe_tags)
+ ]
+ for package, maybe_tags in imports.items()
+ }
+
+
+def collapse_imports(
+ imports: ParsedImportDict | ImmutableParsedImportDict,
+) -> ParsedImportDict:
"""Remove all duplicate ImportVar within an ImportDict.
Args:
@@ -33,10 +78,20 @@ def collapse_imports(imports: ImportDict) -> ImportDict:
Returns:
The collapsed import dict.
"""
- return {lib: list(set(import_vars)) for lib, import_vars in imports.items()}
+ return {
+ lib: (
+ list(set(import_vars))
+ if isinstance(import_vars, list)
+ else list(import_vars)
+ )
+ for lib, import_vars in (
+ imports if isinstance(imports, tuple) else imports.items()
+ )
+ }
-class ImportVar(Base):
+@dataclasses.dataclass(order=True, frozen=True)
+class ImportVar:
"""An import var."""
# The name of the import tag.
@@ -72,22 +127,8 @@ class ImportVar(Base):
else:
return self.tag or ""
- def __hash__(self) -> int:
- """Define a hash function for the import var.
- Returns:
- The hash of the var.
- """
- return hash(
- (
- self.tag,
- self.is_default,
- self.alias,
- self.install,
- self.render,
- self.transpile,
- )
- )
-
-
-ImportDict = Dict[str, List[ImportVar]]
+ImportTypes = Union[str, ImportVar, List[Union[str, ImportVar]], List[ImportVar]]
+ImportDict = Dict[str, ImportTypes]
+ParsedImportDict = Dict[str, List[ImportVar]]
+ImmutableParsedImportDict = Tuple[Tuple[str, Tuple[ImportVar, ...]], ...]
diff --git a/reflex/utils/lazy_loader.py b/reflex/utils/lazy_loader.py
new file mode 100644
index 000000000..61e3967e5
--- /dev/null
+++ b/reflex/utils/lazy_loader.py
@@ -0,0 +1,34 @@
+"""Module to implement lazy loading in reflex."""
+
+import copy
+
+import lazy_loader as lazy
+
+
+def attach(package_name, submodules=None, submod_attrs=None):
+ """Replaces a package's __getattr__, __dir__, and __all__ attributes using lazy.attach.
+ The lazy loader __getattr__ doesn't support tuples as list values. We needed to add
+ this functionality (tuples) in Reflex to support 'import as _' statements. This function
+ reformats the submod_attrs dictionary to flatten the module list before passing it to
+ lazy_loader.
+
+ Args:
+ package_name: name of the package.
+ submodules : List of submodules to attach.
+ submod_attrs : Dictionary of submodule -> list of attributes / functions.
+ These attributes are imported as they are used.
+
+ Returns:
+ __getattr__, __dir__, __all__
+ """
+ _submod_attrs = copy.deepcopy(submod_attrs)
+ if _submod_attrs:
+ for k, v in _submod_attrs.items():
+ # when flattening the list, only keep the alias in the tuple(mod[1])
+ _submod_attrs[k] = [
+ mod if not isinstance(mod, tuple) else mod[1] for mod in v
+ ]
+
+ return lazy.attach(
+ package_name=package_name, submodules=submodules, submod_attrs=_submod_attrs
+ )
diff --git a/reflex/utils/net.py b/reflex/utils/net.py
new file mode 100644
index 000000000..2c6f22764
--- /dev/null
+++ b/reflex/utils/net.py
@@ -0,0 +1,41 @@
+"""Helpers for downloading files from the network."""
+
+import httpx
+
+from ..config import environment
+from . import console
+
+
+def _httpx_verify_kwarg() -> bool:
+ """Get the value of the HTTPX verify keyword argument.
+
+ Returns:
+ True if SSL verification is enabled, False otherwise
+ """
+ return not environment.SSL_NO_VERIFY
+
+
+def get(url: str, **kwargs) -> httpx.Response:
+ """Make an HTTP GET request.
+
+ Args:
+ url: The URL to request.
+ **kwargs: Additional keyword arguments to pass to httpx.get.
+
+ Returns:
+ The response object.
+
+ Raises:
+ httpx.ConnectError: If the connection cannot be established.
+ """
+ kwargs.setdefault("verify", _httpx_verify_kwarg())
+ try:
+ return httpx.get(url, **kwargs)
+ except httpx.ConnectError as err:
+ if "CERTIFICATE_VERIFY_FAILED" in str(err):
+ # If the error is a certificate verification error, recommend mitigating steps.
+ console.error(
+ f"Certificate verification failed for {url}. Set environment variable SSL_CERT_FILE to the "
+ "path of the certificate file or SSL_NO_VERIFY=1 to disable verification."
+ )
+ raise
diff --git a/reflex/utils/path_ops.py b/reflex/utils/path_ops.py
index 3073dca0e..ee93b24cf 100644
--- a/reflex/utils/path_ops.py
+++ b/reflex/utils/path_ops.py
@@ -9,24 +9,26 @@ import shutil
from pathlib import Path
from reflex import constants
+from reflex.config import environment
# Shorthand for join.
join = os.linesep.join
-def rm(path: str):
+def rm(path: str | Path):
"""Remove a file or directory.
Args:
path: The path to the file or directory.
"""
- if os.path.isdir(path):
+ path = Path(path)
+ if path.is_dir():
shutil.rmtree(path)
- elif os.path.isfile(path):
- os.remove(path)
+ elif path.is_file():
+ path.unlink()
-def cp(src: str, dest: str, overwrite: bool = True) -> bool:
+def cp(src: str | Path, dest: str | Path, overwrite: bool = True) -> bool:
"""Copy a file or directory.
Args:
@@ -37,11 +39,12 @@ def cp(src: str, dest: str, overwrite: bool = True) -> bool:
Returns:
Whether the copy was successful.
"""
+ src, dest = Path(src), Path(dest)
if src == dest:
return False
- if not overwrite and os.path.exists(dest):
+ if not overwrite and dest.exists():
return False
- if os.path.isdir(src):
+ if src.is_dir():
rm(dest)
shutil.copytree(src, dest)
else:
@@ -49,7 +52,7 @@ def cp(src: str, dest: str, overwrite: bool = True) -> bool:
return True
-def mv(src: str, dest: str, overwrite: bool = True) -> bool:
+def mv(src: str | Path, dest: str | Path, overwrite: bool = True) -> bool:
"""Move a file or directory.
Args:
@@ -60,25 +63,38 @@ def mv(src: str, dest: str, overwrite: bool = True) -> bool:
Returns:
Whether the move was successful.
"""
+ src, dest = Path(src), Path(dest)
if src == dest:
return False
- if not overwrite and os.path.exists(dest):
+ if not overwrite and dest.exists():
return False
rm(dest)
shutil.move(src, dest)
return True
-def mkdir(path: str):
+def mkdir(path: str | Path):
"""Create a directory.
Args:
path: The path to the directory.
"""
- os.makedirs(path, exist_ok=True)
+ Path(path).mkdir(parents=True, exist_ok=True)
-def ln(src: str, dest: str, overwrite: bool = False) -> bool:
+def ls(path: str | Path) -> list[Path]:
+ """List the contents of a directory.
+
+ Args:
+ path: The path to the directory.
+
+ Returns:
+ A list of paths to the contents of the directory.
+ """
+ return list(Path(path).iterdir())
+
+
+def ln(src: str | Path, dest: str | Path, overwrite: bool = False) -> bool:
"""Create a symbolic link.
Args:
@@ -89,19 +105,20 @@ def ln(src: str, dest: str, overwrite: bool = False) -> bool:
Returns:
Whether the link was successful.
"""
+ src, dest = Path(src), Path(dest)
if src == dest:
return False
- if not overwrite and (os.path.exists(dest) or os.path.islink(dest)):
+ if not overwrite and (dest.exists() or dest.is_symlink()):
return False
- if os.path.isdir(src):
+ if src.is_dir():
rm(dest)
- os.symlink(src, dest, target_is_directory=True)
+ src.symlink_to(dest, target_is_directory=True)
else:
- os.symlink(src, dest)
+ src.symlink_to(dest)
return True
-def which(program: str) -> str | None:
+def which(program: str | Path) -> str | Path | None:
"""Find the path to an executable.
Args:
@@ -110,19 +127,38 @@ def which(program: str) -> str | None:
Returns:
The path to the executable.
"""
- return shutil.which(program)
+ return shutil.which(str(program))
-def get_node_bin_path() -> str | None:
+def use_system_node() -> bool:
+ """Check if the system node should be used.
+
+ Returns:
+ Whether the system node should be used.
+ """
+ return environment.REFLEX_USE_SYSTEM_NODE
+
+
+def use_system_bun() -> bool:
+ """Check if the system bun should be used.
+
+ Returns:
+ Whether the system bun should be used.
+ """
+ return environment.REFLEX_USE_SYSTEM_BUN
+
+
+def get_node_bin_path() -> Path | None:
"""Get the node binary dir path.
Returns:
The path to the node bin folder.
"""
- if not os.path.exists(constants.Node.BIN_PATH):
+ bin_path = Path(constants.Node.BIN_PATH)
+ if not bin_path.exists():
str_path = which("node")
- return str(Path(str_path).parent.resolve()) if str_path else str_path
- return str(Path(constants.Node.BIN_PATH).resolve())
+ return Path(str_path).parent.resolve() if str_path else None
+ return bin_path.resolve()
def get_node_path() -> str | None:
@@ -131,9 +167,11 @@ def get_node_path() -> str | None:
Returns:
The path to the node binary file.
"""
- if not os.path.exists(constants.Node.PATH):
- return which("node")
- return constants.Node.PATH
+ node_path = Path(constants.Node.PATH)
+ if use_system_node() or not node_path.exists():
+ system_node_path = which("node")
+ return str(system_node_path) if system_node_path else None
+ return str(node_path)
def get_npm_path() -> str | None:
@@ -142,12 +180,14 @@ def get_npm_path() -> str | None:
Returns:
The path to the npm binary file.
"""
- if not os.path.exists(constants.Node.PATH):
- return which("npm")
- return constants.Node.NPM_PATH
+ npm_path = Path(constants.Node.NPM_PATH)
+ if use_system_node() or not npm_path.exists():
+ system_npm_path = which("npm")
+ return str(system_npm_path) if system_npm_path else None
+ return str(npm_path)
-def update_json_file(file_path: str, update_dict: dict[str, int | str]):
+def update_json_file(file_path: str | Path, update_dict: dict[str, int | str]):
"""Update the contents of a json file.
Args:
@@ -164,7 +204,7 @@ def update_json_file(file_path: str, update_dict: dict[str, int | str]):
# Read the existing json object from the file.
json_object = {}
- if fp.stat().st_size == 0:
+ if fp.stat().st_size:
with open(fp) as f:
json_object = json.load(f)
@@ -176,7 +216,7 @@ def update_json_file(file_path: str, update_dict: dict[str, int | str]):
json.dump(json_object, f, ensure_ascii=False)
-def find_replace(directory: str, find: str, replace: str):
+def find_replace(directory: str | Path, find: str, replace: str):
"""Recursively find and replace text in files in a directory.
Args:
@@ -184,11 +224,10 @@ def find_replace(directory: str, find: str, replace: str):
find: The text to find.
replace: The text to replace.
"""
+ directory = Path(directory)
for root, _dirs, files in os.walk(directory):
for file in files:
- filepath = os.path.join(root, file)
- with open(filepath, "r", encoding="utf-8") as f:
- text = f.read()
+ filepath = Path(root, file)
+ text = filepath.read_text(encoding="utf-8")
text = re.sub(find, replace, text)
- with open(filepath, "w") as f:
- f.write(text)
+ filepath.write_text(text, encoding="utf-8")
diff --git a/reflex/utils/prerequisites.py b/reflex/utils/prerequisites.py
index de4741c1e..d70e7706f 100644
--- a/reflex/utils/prerequisites.py
+++ b/reflex/utils/prerequisites.py
@@ -2,10 +2,11 @@
from __future__ import annotations
+import contextlib
+import dataclasses
import functools
-import glob
import importlib
-import inspect
+import importlib.metadata
import json
import os
import platform
@@ -15,33 +16,34 @@ import shutil
import stat
import sys
import tempfile
+import time
import zipfile
from datetime import datetime
-from fileinput import FileInput
from pathlib import Path
from types import ModuleType
from typing import Callable, List, Optional
import httpx
-import pkg_resources
import typer
from alembic.util.exc import CommandError
from packaging import version
from redis import Redis as RedisSync
+from redis import exceptions
from redis.asyncio import Redis
-import reflex
from reflex import constants, model
-from reflex.base import Base
from reflex.compiler import templates
-from reflex.config import Config, get_config
-from reflex.utils import console, path_ops, processes
+from reflex.config import Config, environment, get_config
+from reflex.utils import console, net, path_ops, processes
+from reflex.utils.exceptions import GeneratedCodeHasNoFunctionDefs
from reflex.utils.format import format_library_name
+from reflex.utils.registry import _get_npm_registry
CURRENTLY_INSTALLING_NODE = False
-class Template(Base):
+@dataclasses.dataclass(frozen=True)
+class Template:
"""A template for a Reflex app."""
name: str
@@ -50,7 +52,8 @@ class Template(Base):
demo_url: str
-class CpuInfo(Base):
+@dataclasses.dataclass(frozen=True)
+class CpuInfo:
"""Model to save cpu info."""
manufacturer_id: Optional[str]
@@ -58,6 +61,29 @@ class CpuInfo(Base):
address_width: Optional[int]
+def get_web_dir() -> Path:
+ """Get the working directory for the next.js commands.
+
+ Can be overridden with REFLEX_WEB_WORKDIR.
+
+ Returns:
+ The working directory.
+ """
+ return environment.REFLEX_WEB_WORKDIR
+
+
+def _python_version_check():
+ """Emit deprecation warning for deprecated python versions."""
+ # Check for end-of-life python versions.
+ if sys.version_info < (3, 10):
+ console.deprecate(
+ feature_name="Support for Python 3.9 and older",
+ reason="please upgrade to Python 3.10 or newer",
+ deprecation_version="0.6.0",
+ removal_version="0.7.0",
+ )
+
+
def check_latest_package_version(package_name: str):
"""Check if the latest version of the package is installed.
@@ -66,19 +92,20 @@ def check_latest_package_version(package_name: str):
"""
try:
# Get the latest version from PyPI
- current_version = pkg_resources.get_distribution(package_name).version
+ current_version = importlib.metadata.version(package_name)
url = f"https://pypi.org/pypi/{package_name}/json"
- response = httpx.get(url)
+ response = net.get(url)
latest_version = response.json()["info"]["version"]
- if (
- version.parse(current_version) < version.parse(latest_version)
- and not get_or_set_last_reflex_version_check_datetime()
- ):
- # only show a warning when the host version is outdated and
- # the last_version_check_datetime is not set in reflex.json
+ if get_or_set_last_reflex_version_check_datetime():
+ # Versions were already checked and saved in reflex.json, no need to warn again
+ return
+ if version.parse(current_version) < version.parse(latest_version):
+ # Show a warning when the host version is older than PyPI version
console.warn(
f"Your version ({current_version}) of {package_name} is out of date. Upgrade to {latest_version} with 'pip install {package_name} --upgrade'"
)
+ # Check for depreacted python versions
+ _python_version_check()
except Exception:
pass
@@ -91,18 +118,26 @@ def get_or_set_last_reflex_version_check_datetime():
Returns:
The last version check datetime.
"""
- if not os.path.exists(constants.Reflex.JSON):
+ reflex_json_file = get_web_dir() / constants.Reflex.JSON
+ if not reflex_json_file.exists():
return None
# Open and read the file
- with open(constants.Reflex.JSON, "r") as file:
- data: dict = json.load(file)
+ data = json.loads(reflex_json_file.read_text())
last_version_check_datetime = data.get("last_version_check_datetime")
if not last_version_check_datetime:
data.update({"last_version_check_datetime": str(datetime.now())})
- path_ops.update_json_file(constants.Reflex.JSON, data)
+ path_ops.update_json_file(reflex_json_file, data)
return last_version_check_datetime
+def set_last_reflex_run_time():
+ """Set the last Reflex run time."""
+ path_ops.update_json_file(
+ get_web_dir() / constants.Reflex.JSON,
+ {"last_reflex_run_datetime": str(datetime.now())},
+ )
+
+
def check_node_version() -> bool:
"""Check the version of Node.js.
@@ -110,14 +145,9 @@ def check_node_version() -> bool:
Whether the version of Node.js is valid.
"""
current_version = get_node_version()
- if current_version:
- # Compare the version numbers
- return (
- current_version >= version.parse(constants.Node.MIN_VERSION)
- if constants.IS_WINDOWS
- else current_version == version.parse(constants.Node.VERSION)
- )
- return False
+ return current_version is not None and current_version >= version.parse(
+ constants.Node.MIN_VERSION
+ )
def get_node_version() -> version.Version | None:
@@ -163,7 +193,7 @@ def get_bun_version() -> version.Version | None:
"""
try:
# Run the bun -v command and capture the output
- result = processes.new_process([get_config().bun_path, "-v"], run=True)
+ result = processes.new_process([str(get_config().bun_path), "-v"], run=True)
return version.parse(result.stdout) # type: ignore
except FileNotFoundError:
return None
@@ -181,9 +211,14 @@ def get_install_package_manager() -> str | None:
Returns:
The path to the package manager.
"""
- if constants.IS_WINDOWS and not is_windows_bun_supported():
+ if (
+ constants.IS_WINDOWS
+ and not is_windows_bun_supported()
+ or windows_check_onedrive_in_path()
+ or windows_npm_escape_hatch()
+ ):
return get_package_manager()
- return get_config().bun_path
+ return str(get_config().bun_path)
def get_package_manager() -> str | None:
@@ -199,6 +234,24 @@ def get_package_manager() -> str | None:
return npm_path
+def windows_check_onedrive_in_path() -> bool:
+ """For windows, check if oneDrive is present in the project dir path.
+
+ Returns:
+ If oneDrive is in the path of the project directory.
+ """
+ return "onedrive" in str(Path.cwd()).lower()
+
+
+def windows_npm_escape_hatch() -> bool:
+ """For windows, if the user sets REFLEX_USE_NPM, use npm instead of bun.
+
+ Returns:
+ If the user has set REFLEX_USE_NPM.
+ """
+ return environment.REFLEX_USE_NPM
+
+
def get_app(reload: bool = False) -> ModuleType:
"""Get the app module based on the default config.
@@ -210,9 +263,8 @@ def get_app(reload: bool = False) -> ModuleType:
Raises:
RuntimeError: If the app name is not set in the config.
- exceptions.ReflexError: Reflex specific errors.
"""
- from reflex.utils import exceptions, telemetry
+ from reflex.utils import telemetry
try:
os.environ[constants.RELOAD_CONFIG] = str(reload)
@@ -236,8 +288,8 @@ def get_app(reload: bool = False) -> ModuleType:
importlib.reload(app)
return app
- except exceptions.ReflexError as ex:
- telemetry.send("error", context="frontend", detail=str(ex))
+ except Exception as ex:
+ telemetry.send_error(ex, context="frontend")
raise
@@ -253,7 +305,7 @@ def get_compiled_app(reload: bool = False, export: bool = False) -> ModuleType:
"""
app_module = get_app(reload=reload)
app = getattr(app_module, constants.CompileVars.APP)
- # For py3.8 and py3.9 compatibility when redis is used, we MUST add any decorator pages
+ # For py3.9 compatibility when redis is used, we MUST add any decorator pages
# before compiling the app in a thread to avoid event loop error (REF-2172).
app._apply_decorated_pages()
app._compile(export=export)
@@ -290,37 +342,43 @@ def parse_redis_url() -> str | dict | None:
"""Parse the REDIS_URL in config if applicable.
Returns:
- If redis-py syntax, return the URL as it is. Otherwise, return the host/port/db as a dict.
+ If url is non-empty, return the URL as it is.
+
+ Raises:
+ ValueError: If the REDIS_URL is not a supported scheme.
"""
config = get_config()
if not config.redis_url:
return None
- if config.redis_url.startswith(("redis://", "rediss://", "unix://")):
- return config.redis_url
- console.deprecate(
- feature_name="host[:port] style redis urls",
- reason="redis-py url syntax is now being used",
- deprecation_version="0.3.6",
- removal_version="0.6.0",
- )
- redis_url, has_port, redis_port = config.redis_url.partition(":")
- if not has_port:
- redis_port = 6379
- console.info(f"Using redis at {config.redis_url}")
- return dict(host=redis_url, port=int(redis_port), db=0)
+ if not config.redis_url.startswith(("redis://", "rediss://", "unix://")):
+ raise ValueError(
+ "REDIS_URL must start with 'redis://', 'rediss://', or 'unix://'."
+ )
+ return config.redis_url
-def get_production_backend_url() -> str:
- """Get the production backend URL.
+async def get_redis_status() -> bool | None:
+ """Checks the status of the Redis connection.
+
+ Attempts to connect to Redis and send a ping command to verify connectivity.
Returns:
- The production backend URL.
+ bool or None: The status of the Redis connection:
+ - True: Redis is accessible and responding.
+ - False: Redis is not accessible due to a connection error.
+ - None: Redis not used i.e redis_url is not set in rxconfig.
"""
- config = get_config()
- return constants.PRODUCTION_BACKEND_URL.format(
- username=config.username,
- app_name=config.app_name,
- )
+ try:
+ status = True
+ redis_client = get_redis_sync()
+ if redis_client is not None:
+ redis_client.ping()
+ else:
+ status = None
+ except exceptions.RedisError:
+ status = False
+
+ return status
def validate_app_name(app_name: str | None = None) -> str:
@@ -337,9 +395,7 @@ def validate_app_name(app_name: str | None = None) -> str:
Raises:
Exit: if the app directory name is reflex or if the name is not standard for a python package name.
"""
- app_name = (
- app_name if app_name else os.getcwd().split(os.path.sep)[-1].replace("-", "_")
- )
+ app_name = app_name if app_name else Path.cwd().name.replace("-", "_")
# Make sure the app is not named "reflex".
if app_name.lower() == constants.Reflex.MODULE_NAME:
console.error(
@@ -373,7 +429,7 @@ def create_config(app_name: str):
def initialize_gitignore(
- gitignore_file: str = constants.GitIgnore.FILE,
+ gitignore_file: Path = constants.GitIgnore.FILE,
files_to_ignore: set[str] = constants.GitIgnore.DEFAULTS,
):
"""Initialize the template .gitignore file.
@@ -383,14 +439,23 @@ def initialize_gitignore(
files_to_ignore: The files to add to the .gitignore file.
"""
# Combine with the current ignored files.
- if os.path.exists(gitignore_file):
- with open(gitignore_file, "r") as f:
- files_to_ignore |= set([line.strip() for line in f.readlines()])
+ current_ignore: set[str] = set()
+ if gitignore_file.exists():
+ current_ignore |= set(
+ line.strip() for line in gitignore_file.read_text().splitlines()
+ )
+
+ if files_to_ignore == current_ignore:
+ console.debug(f"{gitignore_file} already up to date.")
+ return
+ files_to_ignore |= current_ignore
# Write files to the .gitignore file.
- with open(gitignore_file, "w", newline="\n") as f:
- console.debug(f"Creating {gitignore_file}")
- f.write(f"{(path_ops.join(sorted(files_to_ignore))).lstrip()}")
+ gitignore_file.touch(exist_ok=True)
+ console.debug(f"Creating {gitignore_file}")
+ gitignore_file.write_text(
+ "\n".join(sorted(files_to_ignore)) + "\n",
+ )
def initialize_requirements_txt():
@@ -483,8 +548,8 @@ def initialize_app_directory(
# Rename the template app to the app name.
path_ops.mv(template_code_dir_name, app_name)
path_ops.mv(
- os.path.join(app_name, template_name + constants.Ext.PY),
- os.path.join(app_name, app_name + constants.Ext.PY),
+ Path(app_name) / (template_name + constants.Ext.PY),
+ Path(app_name) / (app_name + constants.Ext.PY),
)
# Fix up the imports.
@@ -504,12 +569,11 @@ def get_project_hash(raise_on_fail: bool = False) -> int | None:
Returns:
project_hash: The app hash.
"""
- if not os.path.exists(constants.Reflex.JSON) and not raise_on_fail:
+ json_file = get_web_dir() / constants.Reflex.JSON
+ if not json_file.exists() and not raise_on_fail:
return None
- # Open and read the file
- with open(constants.Reflex.JSON, "r") as file:
- data = json.load(file)
- return data.get("project_hash")
+ data = json.loads(json_file.read_text())
+ return data.get("project_hash")
def initialize_web_directory():
@@ -519,11 +583,11 @@ def initialize_web_directory():
# Re-use the hash if one is already created, so we don't over-write it when running reflex init
project_hash = get_project_hash()
- path_ops.cp(constants.Templates.Dirs.WEB_TEMPLATE, constants.Dirs.WEB)
+ path_ops.cp(constants.Templates.Dirs.WEB_TEMPLATE, str(get_web_dir()))
initialize_package_json()
- path_ops.mkdir(constants.Dirs.WEB_ASSETS)
+ path_ops.mkdir(get_web_dir() / constants.Dirs.PUBLIC)
update_next_config()
@@ -546,10 +610,18 @@ def _compile_package_json():
def initialize_package_json():
"""Render and write in .web the package.json file."""
- output_path = constants.PackageJson.PATH
+ output_path = get_web_dir() / constants.PackageJson.PATH
code = _compile_package_json()
- with open(output_path, "w") as file:
- file.write(code)
+ output_path.write_text(code)
+
+ best_registry = _get_npm_registry()
+ bun_config_path = get_web_dir() / constants.Bun.CONFIG_PATH
+ bun_config_path.write_text(
+ f"""
+[install]
+registry = "{best_registry}"
+"""
+ )
def init_reflex_json(project_hash: int | None):
@@ -574,7 +646,7 @@ def init_reflex_json(project_hash: int | None):
"version": constants.Reflex.VERSION,
"project_hash": project_hash,
}
- path_ops.update_json_file(constants.Reflex.JSON, reflex_json)
+ path_ops.update_json_file(get_web_dir() / constants.Reflex.JSON, reflex_json)
def update_next_config(export=False, transpile_packages: Optional[List[str]] = None):
@@ -584,7 +656,7 @@ def update_next_config(export=False, transpile_packages: Optional[List[str]] = N
export: if the method run during reflex export.
transpile_packages: list of packages to transpile via next.config.js.
"""
- next_config_file = Path(constants.Dirs.WEB, constants.Next.CONFIG_FILE)
+ next_config_file = get_web_dir() / constants.Next.CONFIG_FILE
next_config = _update_next_config(
get_config(), export=export, transpile_packages=transpile_packages
@@ -603,8 +675,9 @@ def _update_next_config(
next_config = {
"basePath": config.frontend_path or "",
"compress": config.next_compression,
- "reactStrictMode": True,
+ "reactStrictMode": config.react_strict_mode,
"trailingSlash": True,
+ "staticPageGenerationTimeout": config.static_page_generation_timeout,
}
if transpile_packages:
next_config["transpilePackages"] = list(
@@ -621,7 +694,7 @@ def _update_next_config(
def remove_existing_bun_installation():
"""Remove existing bun installation."""
console.debug("Removing existing bun installation.")
- if os.path.exists(get_config().bun_path):
+ if Path(get_config().bun_path).exists():
path_ops.rm(constants.Bun.ROOT_PATH)
@@ -636,7 +709,7 @@ def download_and_run(url: str, *args, show_status: bool = False, **env):
"""
# Download the script
console.debug(f"Downloading {url}")
- response = httpx.get(url)
+ response = net.get(url)
if response.status_code != httpx.codes.OK:
response.raise_for_status()
@@ -661,16 +734,16 @@ def download_and_extract_fnm_zip():
# Download the zip file
url = constants.Fnm.INSTALL_URL
console.debug(f"Downloading {url}")
- fnm_zip_file = os.path.join(constants.Fnm.DIR, f"{constants.Fnm.FILENAME}.zip")
+ fnm_zip_file = constants.Fnm.DIR / f"{constants.Fnm.FILENAME}.zip"
# Function to download and extract the FNM zip release.
try:
# Download the FNM zip release.
# TODO: show progress to improve UX
- with httpx.stream("GET", url, follow_redirects=True) as response:
- response.raise_for_status()
- with open(fnm_zip_file, "wb") as output_file:
- for chunk in response.iter_bytes():
- output_file.write(chunk)
+ response = net.get(url, follow_redirects=True)
+ response.raise_for_status()
+ with open(fnm_zip_file, "wb") as output_file:
+ for chunk in response.iter_bytes():
+ output_file.write(chunk)
# Extract the downloaded zip file.
with zipfile.ZipFile(fnm_zip_file, "r") as zip_ref:
@@ -700,7 +773,7 @@ def install_node():
return
path_ops.mkdir(constants.Fnm.DIR)
- if not os.path.exists(constants.Fnm.EXE):
+ if not constants.Fnm.EXE.exists():
download_and_extract_fnm_zip()
if constants.IS_WINDOWS:
@@ -744,13 +817,20 @@ def install_bun():
Raises:
FileNotFoundError: If required packages are not found.
"""
- if constants.IS_WINDOWS and not is_windows_bun_supported():
- console.warn(
- "Bun for Windows is currently only available for x86 64-bit Windows. Installation will fall back on npm."
- )
+ win_supported = is_windows_bun_supported()
+ one_drive_in_path = windows_check_onedrive_in_path()
+ if constants.IS_WINDOWS and not win_supported or one_drive_in_path:
+ if not win_supported:
+ console.warn(
+ "Bun for Windows is currently only available for x86 64-bit Windows. Installation will fall back on npm."
+ )
+ if one_drive_in_path:
+ console.warn(
+ "Creating project directories in OneDrive is not recommended for bun usage on windows. This will fallback to npm."
+ )
# Skip if bun is already installed.
- if os.path.exists(get_config().bun_path) and get_bun_version() == version.parse(
+ if Path(get_config().bun_path).exists() and get_bun_version() == version.parse(
constants.Bun.VERSION
):
console.debug("Skipping bun installation as it is already installed.")
@@ -765,7 +845,7 @@ def install_bun():
f"irm {constants.Bun.WINDOWS_INSTALL_URL}|iex",
],
env={
- "BUN_INSTALL": constants.Bun.ROOT_PATH,
+ "BUN_INSTALL": str(constants.Bun.ROOT_PATH),
"BUN_VERSION": constants.Bun.VERSION,
},
shell=True,
@@ -781,25 +861,26 @@ def install_bun():
download_and_run(
constants.Bun.INSTALL_URL,
f"bun-v{constants.Bun.VERSION}",
- BUN_INSTALL=constants.Bun.ROOT_PATH,
+ BUN_INSTALL=str(constants.Bun.ROOT_PATH),
)
-def _write_cached_procedure_file(payload: str, cache_file: str):
- with open(cache_file, "w") as f:
- f.write(payload)
+def _write_cached_procedure_file(payload: str, cache_file: str | Path):
+ cache_file = Path(cache_file)
+ cache_file.write_text(payload)
-def _read_cached_procedure_file(cache_file: str) -> str | None:
- if os.path.exists(cache_file):
- with open(cache_file, "r") as f:
- return f.read()
+def _read_cached_procedure_file(cache_file: str | Path) -> str | None:
+ cache_file = Path(cache_file)
+ if cache_file.exists():
+ return cache_file.read_text()
return None
-def _clear_cached_procedure_file(cache_file: str):
- if os.path.exists(cache_file):
- os.remove(cache_file)
+def _clear_cached_procedure_file(cache_file: str | Path):
+ cache_file = Path(cache_file)
+ if cache_file.exists():
+ cache_file.unlink()
def cached_procedure(cache_file: str, payload_fn: Callable[..., str]):
@@ -829,9 +910,7 @@ def cached_procedure(cache_file: str, payload_fn: Callable[..., str]):
@cached_procedure(
- cache_file=os.path.join(
- constants.Dirs.WEB, "reflex.install_frontend_packages.cached"
- ),
+ cache_file=str(get_web_dir() / "reflex.install_frontend_packages.cached"),
payload_fn=lambda p, c: f"{repr(sorted(list(p)))},{c.json()}",
)
def install_frontend_packages(packages: set[str], config: Config):
@@ -850,6 +929,7 @@ def install_frontend_packages(packages: set[str], config: Config):
if not constants.IS_WINDOWS
or constants.IS_WINDOWS
and is_windows_bun_supported()
+ and not windows_check_onedrive_in_path()
else None
)
processes.run_process_with_fallback(
@@ -857,7 +937,7 @@ def install_frontend_packages(packages: set[str], config: Config):
fallback=fallback_command,
analytics_enabled=True,
show_status_message="Installing base frontend packages",
- cwd=constants.Dirs.WEB,
+ cwd=get_web_dir(),
shell=constants.IS_WINDOWS,
)
@@ -873,7 +953,7 @@ def install_frontend_packages(packages: set[str], config: Config):
fallback=fallback_command,
analytics_enabled=True,
show_status_message="Installing tailwind",
- cwd=constants.Dirs.WEB,
+ cwd=get_web_dir(),
shell=constants.IS_WINDOWS,
)
@@ -884,7 +964,7 @@ def install_frontend_packages(packages: set[str], config: Config):
fallback=fallback_command,
analytics_enabled=True,
show_status_message="Installing frontend packages from config and components",
- cwd=constants.Dirs.WEB,
+ cwd=get_web_dir(),
shell=constants.IS_WINDOWS,
)
@@ -901,7 +981,7 @@ def needs_reinit(frontend: bool = True) -> bool:
Raises:
Exit: If the app is not initialized.
"""
- if not os.path.exists(constants.Config.FILE):
+ if not constants.Config.FILE.exists():
console.error(
f"[cyan]{constants.Config.FILE}[/cyan] not found. Move to the root folder of your project, or run [bold]{constants.Reflex.MODULE_NAME} init[/bold] to start a new project."
)
@@ -912,11 +992,11 @@ def needs_reinit(frontend: bool = True) -> bool:
return False
# Make sure the .reflex directory exists.
- if not os.path.exists(constants.Reflex.DIR):
+ if not environment.REFLEX_DIR.exists():
return True
# Make sure the .web directory exists in frontend mode.
- if not os.path.exists(constants.Dirs.WEB):
+ if not get_web_dir().exists():
return True
# If the template is out of date, then we need to re-init
@@ -924,20 +1004,13 @@ def needs_reinit(frontend: bool = True) -> bool:
return True
if constants.IS_WINDOWS:
- import uvicorn
-
- uvi_ver = uvicorn.__version__
console.warn(
"""Windows Subsystem for Linux (WSL) is recommended for improving initial install times."""
)
- if sys.version_info >= (3, 12) and uvi_ver != "0.24.0.post1":
- console.warn(
- f"""On Python 3.12, `uvicorn==0.24.0.post1` is recommended for improved hot reload times. Found {uvi_ver} instead."""
- )
- if sys.version_info < (3, 12) and uvi_ver != "0.20.0":
+ if windows_check_onedrive_in_path():
console.warn(
- f"""On Python < 3.12, `uvicorn==0.20.0` is recommended for improved hot reload times. Found {uvi_ver} instead."""
+ "Creating project directories in OneDrive may lead to performance issues. For optimal performance, It is recommended to avoid using OneDrive for your reflex app."
)
# No need to reinitialize if the app is already initialized.
return False
@@ -949,10 +1022,10 @@ def is_latest_template() -> bool:
Returns:
Whether the app is using the latest template.
"""
- if not os.path.exists(constants.Reflex.JSON):
+ json_file = get_web_dir() / constants.Reflex.JSON
+ if not json_file.exists():
return False
- with open(constants.Reflex.JSON) as f: # type: ignore
- app_version = json.load(f)["version"]
+ app_version = json.loads(json_file.read_text()).get("version")
return app_version == constants.Reflex.VERSION
@@ -965,6 +1038,8 @@ def validate_bun():
# if a custom bun path is provided, make sure its valid
# This is specific to non-FHS OS
bun_path = get_config().bun_path
+ if path_ops.use_system_bun():
+ bun_path = path_ops.which("bun")
if bun_path != constants.Bun.DEFAULT_PATH:
console.info(f"Using custom Bun path: {bun_path}")
bun_version = get_bun_version()
@@ -1022,25 +1097,21 @@ def ensure_reflex_installation_id() -> Optional[int]:
"""
try:
initialize_reflex_user_directory()
- installation_id_file = os.path.join(constants.Reflex.DIR, "installation_id")
+ installation_id_file = environment.REFLEX_DIR / "installation_id"
installation_id = None
- if os.path.exists(installation_id_file):
- try:
- with open(installation_id_file, "r") as f:
- installation_id = int(f.read())
- except Exception:
+ if installation_id_file.exists():
+ with contextlib.suppress(Exception):
+ installation_id = int(installation_id_file.read_text())
# If anything goes wrong at all... just regenerate.
# Like what? Examples:
# - file not exists
# - file not readable
# - content not parseable as an int
- pass
if installation_id is None:
installation_id = random.getrandbits(128)
- with open(installation_id_file, "w") as f:
- f.write(str(installation_id))
+ installation_id_file.write_text(str(installation_id))
# If we get here, installation_id is definitely set
return installation_id
except Exception as e:
@@ -1051,7 +1122,7 @@ def ensure_reflex_installation_id() -> Optional[int]:
def initialize_reflex_user_directory():
"""Initialize the reflex user directory."""
# Create the reflex directory.
- path_ops.mkdir(constants.Reflex.DIR)
+ path_ops.mkdir(environment.REFLEX_DIR)
def initialize_frontend_dependencies():
@@ -1074,7 +1145,7 @@ def check_db_initialized() -> bool:
Returns:
True if alembic is initialized (or if database is not used).
"""
- if get_config().db_url is not None and not Path(constants.ALEMBIC_CONFIG).exists():
+ if get_config().db_url is not None and not environment.ALEMBIC_CONFIG.exists():
console.error(
"Database is not initialized. Run [bold]reflex db init[/bold] first."
)
@@ -1084,7 +1155,7 @@ def check_db_initialized() -> bool:
def check_schema_up_to_date():
"""Check if the sqlmodel metadata matches the current database schema."""
- if get_config().db_url is None or not Path(constants.ALEMBIC_CONFIG).exists():
+ if get_config().db_url is None or not environment.ALEMBIC_CONFIG.exists():
return
with model.Model.get_db_engine().connect() as connection:
try:
@@ -1134,191 +1205,65 @@ def prompt_for_template(templates: list[Template]) -> str:
return templates[int(template)].name
-def should_show_rx_chakra_migration_instructions() -> bool:
- """Should we show the migration instructions for rx.chakra.* => rx.*?.
+def fetch_app_templates(version: str) -> dict[str, Template]:
+ """Fetch a dict of templates from the templates repo using github API.
+
+ Args:
+ version: The version of the templates to fetch.
Returns:
- bool: True if we should show the migration instructions.
+ The dict of templates.
"""
- if os.getenv("REFLEX_PROMPT_MIGRATE_TO_RX_CHAKRA") == "yes":
- return True
- if not Path(constants.Config.FILE).exists():
- # They are running reflex init for the first time.
- return False
-
- existing_init_reflex_version = None
- reflex_json = Path(constants.Dirs.REFLEX_JSON)
- if reflex_json.exists():
- with reflex_json.open("r") as f:
- data = json.load(f)
- existing_init_reflex_version = data.get("version", None)
-
- if existing_init_reflex_version is None:
- # They clone a reflex app from git for the first time.
- # That app may or may not be 0.4 compatible.
- # So let's just show these instructions THIS TIME.
- return True
-
- if constants.Reflex.VERSION < "0.4":
- return False
- else:
- return existing_init_reflex_version < "0.4"
-
-
-def show_rx_chakra_migration_instructions():
- """Show the migration instructions for rx.chakra.* => rx.*."""
- console.log(
- "Prior to reflex 0.4.0, rx.* components are based on Chakra UI. They are now based on Radix UI. To stick to Chakra UI, use rx.chakra.*."
- )
- console.log("")
- console.log(
- "[bold]Run `reflex script keep-chakra` to automatically update your app."
- )
- console.log("")
- console.log(
- "For more details, please see https://reflex.dev/blog/2024-02-16-reflex-v0.4.0/"
- )
-
-
-def migrate_to_rx_chakra():
- """Migrate rx.button => r.chakra.button, etc."""
- file_pattern = os.path.join(get_config().app_name, "**/*.py")
- file_list = glob.glob(file_pattern, recursive=True)
-
- # Populate with all rx. components that have been moved to rx.chakra.
- patterns = {
- rf"\brx\.{name}\b": f"rx.chakra.{name}"
- for name in _get_rx_chakra_component_to_migrate()
- }
-
- for file_path in file_list:
- with FileInput(file_path, inplace=True) as file:
- for _line_num, line in enumerate(file):
- for old, new in patterns.items():
- line = re.sub(old, new, line)
- print(line, end="")
-
-
-def _get_rx_chakra_component_to_migrate() -> set[str]:
- from reflex.components.chakra import ChakraComponent
-
- rx_chakra_names = set(dir(reflex.chakra))
-
- names_to_migrate = set()
-
- # whitelist names will always be rewritten as rx.chakra.
- whitelist = {
- "ColorModeIcon",
- "MultiSelect",
- "MultiSelectOption",
- "color_mode_icon",
- "multi_select",
- "multi_select_option",
- }
-
- for rx_chakra_name in sorted(rx_chakra_names):
- if rx_chakra_name.startswith("_"):
- continue
-
- rx_chakra_object = getattr(reflex.chakra, rx_chakra_name)
- try:
- if (
- (
- inspect.ismethod(rx_chakra_object)
- and inspect.isclass(rx_chakra_object.__self__)
- and issubclass(rx_chakra_object.__self__, ChakraComponent)
- )
- or (
- inspect.isclass(rx_chakra_object)
- and issubclass(rx_chakra_object, ChakraComponent)
- )
- or rx_chakra_name in whitelist
- ):
- names_to_migrate.add(rx_chakra_name)
-
- except Exception:
- raise
- return names_to_migrate
-
-
-def migrate_to_reflex():
- """Migration from Pynecone to Reflex."""
- # Check if the old config file exists.
- if not os.path.exists(constants.Config.PREVIOUS_FILE):
- return
-
- # Ask the user if they want to migrate.
- action = console.ask(
- "Pynecone project detected. Automatically upgrade to Reflex?",
- choices=["y", "n"],
- )
- if action == "n":
- return
-
- # Rename pcconfig to rxconfig.
- console.log(
- f"[bold]Renaming {constants.Config.PREVIOUS_FILE} to {constants.Config.FILE}"
- )
- os.rename(constants.Config.PREVIOUS_FILE, constants.Config.FILE)
-
- # Find all python files in the app directory.
- file_pattern = os.path.join(get_config().app_name, "**/*.py")
- file_list = glob.glob(file_pattern, recursive=True)
-
- # Add the config file to the list of files to be migrated.
- file_list.append(constants.Config.FILE)
-
- # Migrate all files.
- updates = {
- "Pynecone": "Reflex",
- "pynecone as pc": "reflex as rx",
- "pynecone.io": "reflex.dev",
- "pynecone": "reflex",
- "pc.": "rx.",
- "pcconfig": "rxconfig",
- }
- for file_path in file_list:
- with FileInput(file_path, inplace=True) as file:
- for line in file:
- for old, new in updates.items():
- line = line.replace(old, new)
- print(line, end="")
-
-
-def fetch_app_templates() -> dict[str, Template]:
- """Fetch the list of app templates from the Reflex backend server.
-
- Returns:
- The name and download URL as a dictionary.
- """
- config = get_config()
- if not config.cp_backend_url:
- console.info(
- "Skip fetching App templates. No backend URL is specified in the config."
- )
- return {}
- try:
- response = httpx.get(
- f"{config.cp_backend_url}{constants.Templates.APP_TEMPLATES_ROUTE}"
- )
+ def get_release_by_tag(tag: str) -> dict | None:
+ response = net.get(constants.Reflex.RELEASES_URL)
response.raise_for_status()
- return {
- template["name"]: Template.parse_obj(template)
- for template in response.json()
- }
- except httpx.HTTPError as ex:
- console.info(f"Failed to fetch app templates: {ex}")
- return {}
- except (TypeError, KeyError, json.JSONDecodeError) as tkje:
- console.info(f"Unable to process server response for app templates: {tkje}")
+ releases = response.json()
+ for release in releases:
+ if release["tag_name"] == f"v{tag}":
+ return release
+ return None
+
+ release = get_release_by_tag(version)
+ if release is None:
+ console.warn(f"No templates known for version {version}")
return {}
+ assets = release.get("assets", [])
+ asset = next((a for a in assets if a["name"] == "templates.json"), None)
+ if asset is None:
+ console.warn(f"Templates metadata not found for version {version}")
+ return {}
+ else:
+ templates_url = asset["browser_download_url"]
-def create_config_init_app_from_remote_template(
- app_name: str,
- template_url: str,
-):
+ templates_data = net.get(templates_url, follow_redirects=True).json()["templates"]
+
+ for template in templates_data:
+ if template["name"] == "blank":
+ template["code_url"] = ""
+ continue
+ template["code_url"] = next(
+ (
+ a["browser_download_url"]
+ for a in assets
+ if a["name"] == f"{template['name']}.zip"
+ ),
+ None,
+ )
+
+ filtered_templates = {}
+ for tp in templates_data:
+ if tp["hidden"] or tp["code_url"] is None:
+ continue
+ known_fields = set(f.name for f in dataclasses.fields(Template))
+ filtered_templates[tp["name"]] = Template(
+ **{k: v for k, v in tp.items() if k in known_fields}
+ )
+ return filtered_templates
+
+
+def create_config_init_app_from_remote_template(app_name: str, template_url: str):
"""Create new rxconfig and initialize app using a remote template.
Args:
@@ -1340,7 +1285,7 @@ def create_config_init_app_from_remote_template(
zip_file_path = Path(temp_dir) / "template.zip"
try:
# Note: following redirects can be risky. We only allow this for reflex built templates at the moment.
- response = httpx.get(template_url, follow_redirects=True)
+ response = net.get(template_url, follow_redirects=True)
console.debug(f"Server responded download request: {response}")
response.raise_for_status()
except httpx.HTTPError as he:
@@ -1388,7 +1333,11 @@ def create_config_init_app_from_remote_template(
template_code_dir_name=template_name,
template_dir=template_dir,
)
-
+ req_file = Path("requirements.txt")
+ if req_file.exists() and len(req_file.read_text().splitlines()) > 1:
+ console.info(
+ "Run `pip install -r requirements.txt` to install the required python packages for this template."
+ )
# Clean up the temp directories.
shutil.rmtree(temp_dir)
shutil.rmtree(unzip_dir)
@@ -1408,19 +1357,24 @@ def initialize_app(app_name: str, template: str | None = None):
from reflex.utils import telemetry
# Check if the app is already initialized.
- if os.path.exists(constants.Config.FILE):
+ if constants.Config.FILE.exists():
telemetry.send("reinit")
return
- # Get the available templates
- templates: dict[str, Template] = fetch_app_templates()
+ templates: dict[str, Template] = {}
- # Prompt for a template if not provided.
- if template is None and len(templates) > 0:
- template = prompt_for_template(list(templates.values()))
- elif template is None:
- template = constants.Templates.DEFAULT
- assert template is not None
+ # Don't fetch app templates if the user directly asked for DEFAULT.
+ if template is None or (template != constants.Templates.DEFAULT):
+ try:
+ # Get the available templates
+ templates = fetch_app_templates(constants.Reflex.VERSION)
+ if template is None and len(templates) > 0:
+ template = prompt_for_template(list(templates.values()))
+ except Exception as e:
+ console.warn("Failed to fetch templates. Falling back to default template.")
+ console.debug(f"Error while fetching templates: {e}")
+ finally:
+ template = template or constants.Templates.DEFAULT
# If the blank template is selected, create a blank app.
if template == constants.Templates.DEFAULT:
@@ -1443,14 +1397,77 @@ def initialize_app(app_name: str, template: str | None = None):
else:
console.error(f"Template `{template}` not found.")
raise typer.Exit(1)
+
+ if template_url is None:
+ return
+
create_config_init_app_from_remote_template(
- app_name=app_name,
- template_url=template_url,
+ app_name=app_name, template_url=template_url
)
telemetry.send("init", template=template)
+def initialize_main_module_index_from_generation(app_name: str, generation_hash: str):
+ """Overwrite the `index` function in the main module with reflex.build generated code.
+
+ Args:
+ app_name: The name of the app.
+ generation_hash: The generation hash from reflex.build.
+
+ Raises:
+ GeneratedCodeHasNoFunctionDefs: If the fetched code has no function definitions
+ (the refactored reflex code is expected to have at least one root function defined).
+ """
+ # Download the reflex code for the generation.
+ url = constants.Templates.REFLEX_BUILD_CODE_URL.format(
+ generation_hash=generation_hash
+ )
+ resp = net.get(url)
+ while resp.status_code == httpx.codes.SERVICE_UNAVAILABLE:
+ console.debug("Waiting for the code to be generated...")
+ time.sleep(1)
+ resp = net.get(url)
+ resp.raise_for_status()
+
+ # Determine the name of the last function, which renders the generated code.
+ defined_funcs = re.findall(r"def ([a-zA-Z_]+)\(", resp.text)
+ if not defined_funcs:
+ raise GeneratedCodeHasNoFunctionDefs(
+ f"No function definitions found in generated code from {url!r}."
+ )
+ render_func_name = defined_funcs[-1]
+
+ def replace_content(_match):
+ return "\n".join(
+ [
+ resp.text,
+ "",
+ "" "def index() -> rx.Component:",
+ f" return {render_func_name}()",
+ "",
+ "",
+ ],
+ )
+
+ main_module_path = Path(app_name, app_name + constants.Ext.PY)
+ main_module_code = main_module_path.read_text()
+
+ main_module_code = re.sub(
+ r"def index\(\).*:\n([^\n]\s+.*\n+)+",
+ replace_content,
+ main_module_code,
+ )
+ # Make the app use light mode until flexgen enforces the conversion of
+ # tailwind colors to radix colors.
+ main_module_code = re.sub(
+ r"app\s*=\s*rx\.App\(\s*\)",
+ 'app = rx.App(theme=rx.theme(color_mode="light"))',
+ main_module_code,
+ )
+ main_module_path.write_text(main_module_code)
+
+
def format_address_width(address_width) -> int | None:
"""Cast address width to an int.
@@ -1538,3 +1555,15 @@ def is_windows_bun_supported() -> bool:
and cpu_info.model_name is not None
and "ARM" not in cpu_info.model_name
)
+
+
+def is_generation_hash(template: str) -> bool:
+ """Check if the template looks like a generation hash.
+
+ Args:
+ template: The template name.
+
+ Returns:
+ True if the template is composed of 32 or more hex characters.
+ """
+ return re.match(r"^[0-9a-f]{32,}$", template) is not None
diff --git a/reflex/utils/processes.py b/reflex/utils/processes.py
index cadd87547..a45676c01 100644
--- a/reflex/utils/processes.py
+++ b/reflex/utils/processes.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import collections
import contextlib
+import importlib.metadata
import os
import signal
import subprocess
@@ -58,8 +59,12 @@ def get_process_on_port(port) -> Optional[psutil.Process]:
"""
for proc in psutil.process_iter(["pid", "name", "cmdline"]):
try:
- for conns in proc.connections(kind="inet"):
- if conns.laddr.port == int(port):
+ if importlib.metadata.version("psutil") >= "6.0.0":
+ conns = proc.net_connections(kind="inet") # type: ignore
+ else:
+ conns = proc.connections(kind="inet")
+ for conn in conns:
+ if conn.laddr.port == int(port):
return proc
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
@@ -109,6 +114,33 @@ def change_port(port: str, _type: str) -> str:
return new_port
+def handle_port(service_name: str, port: str, default_port: str) -> str:
+ """Change port if the specified port is in use and is not explicitly specified as a CLI arg or config arg.
+ otherwise tell the user the port is in use and exit the app.
+
+ We make an assumption that when port is the default port,then it hasnt been explicitly set since its not straightforward
+ to know whether a port was explicitly provided by the user unless its any other than the default.
+
+ Args:
+ service_name: The frontend or backend.
+ port: The provided port.
+ default_port: The default port number associated with the specified service.
+
+ Returns:
+ The port to run the service on.
+
+ Raises:
+ Exit:when the port is in use.
+ """
+ if is_process_on_port(port):
+ if int(port) == int(default_port):
+ return change_port(port, service_name)
+ else:
+ console.error(f"{service_name.capitalize()} port: {port} is already in use")
+ raise typer.Exit()
+ return port
+
+
def new_process(args, run: bool = False, show_logs: bool = False, **kwargs):
"""Wrapper over subprocess.Popen to unify the launch of child processes.
@@ -124,7 +156,7 @@ def new_process(args, run: bool = False, show_logs: bool = False, **kwargs):
Raises:
Exit: When attempting to run a command with a None value.
"""
- node_bin_path = path_ops.get_node_bin_path()
+ node_bin_path = str(path_ops.get_node_bin_path())
if not node_bin_path and not prerequisites.CURRENTLY_INSTALLING_NODE:
console.warn(
"The path to the Node binary could not be found. Please ensure that Node is properly "
@@ -135,7 +167,7 @@ def new_process(args, run: bool = False, show_logs: bool = False, **kwargs):
console.error(f"Invalid command: {args}")
raise typer.Exit(1)
# Add the node bin path to the PATH environment variable.
- env = {
+ env: dict[str, str] = {
**os.environ,
"PATH": os.pathsep.join(
[node_bin_path if node_bin_path else "", os.environ["PATH"]]
@@ -158,7 +190,7 @@ def new_process(args, run: bool = False, show_logs: bool = False, **kwargs):
@contextlib.contextmanager
def run_concurrently_context(
- *fns: Union[Callable, Tuple]
+ *fns: Union[Callable, Tuple],
) -> Generator[list[futures.Future], None, None]:
"""Run functions concurrently in a thread pool.
diff --git a/reflex/utils/pyi_generator.py b/reflex/utils/pyi_generator.py
index d14a8af4b..342277cad 100644
--- a/reflex/utils/pyi_generator.py
+++ b/reflex/utils/pyi_generator.py
@@ -9,32 +9,25 @@ import inspect
import logging
import re
import subprocess
-import textwrap
import typing
+from fileinput import FileInput
from inspect import getfullargspec
+from itertools import chain
from multiprocessing import Pool, cpu_count
from pathlib import Path
from types import ModuleType, SimpleNamespace
-from typing import Any, Callable, Iterable, Type, get_args
-
-try:
- import black
- import black.mode
-except ImportError:
- black = None
+from typing import Any, Callable, Iterable, Type, get_args, get_origin
from reflex.components.component import Component
from reflex.utils import types as rx_types
-from reflex.vars import Var
+from reflex.vars.base import Var
logger = logging.getLogger("pyi_generator")
-INIT_FILE = Path("reflex/__init__.pyi").resolve()
PWD = Path(".").resolve()
EXCLUDED_FILES = [
- "__init__.py",
- # "app.py",
+ "app.py",
"component.py",
"bare.py",
"foreach.py",
@@ -65,6 +58,7 @@ EXCLUDED_PROPS = [
DEFAULT_TYPING_IMPORTS = {
"overload",
"Any",
+ "Callable",
"Dict",
# "List",
"Literal",
@@ -72,6 +66,15 @@ DEFAULT_TYPING_IMPORTS = {
"Union",
}
+# TODO: fix import ordering and unused imports with ruff later
+DEFAULT_IMPORTS = {
+ "typing": sorted(DEFAULT_TYPING_IMPORTS),
+ "reflex.components.core.breakpoints": ["Breakpoints"],
+ "reflex.event": ["EventChain", "EventHandler", "EventSpec", "EventType"],
+ "reflex.style": ["Style"],
+ "reflex.vars.base": ["Var"],
+}
+
def _walk_files(path):
"""Walk all files in a path.
@@ -114,6 +117,9 @@ def _get_type_hint(value, type_hint_globals, is_optional=True) -> str:
Returns:
The resolved type hint as a str.
+
+ Raises:
+ TypeError: If the value name is not visible in the type hint globals.
"""
res = ""
args = get_args(value)
@@ -128,6 +134,7 @@ def _get_type_hint(value, type_hint_globals, is_optional=True) -> str:
for arg in value.__args__
if arg is not type(None)
]
+ res_args.sort()
if len(res_args) == 1:
return f"Optional[{res_args[0]}]"
else:
@@ -138,11 +145,12 @@ def _get_type_hint(value, type_hint_globals, is_optional=True) -> str:
_get_type_hint(arg, type_hint_globals, rx_types.is_optional(arg))
for arg in value.__args__
]
+ res_args.sort()
return f"Union[{', '.join(res_args)}]"
if args:
inner_container_type_args = (
- [repr(arg) for arg in args]
+ sorted((repr(arg) for arg in args))
if rx_types.is_literal(value)
else [
_get_type_hint(arg, type_hint_globals, is_optional=False)
@@ -150,9 +158,25 @@ def _get_type_hint(value, type_hint_globals, is_optional=True) -> str:
if arg is not type(None)
]
)
+
+ if (
+ value.__module__ not in ["builtins", "__builtins__"]
+ and value.__name__ not in type_hint_globals
+ ):
+ raise TypeError(
+ f"{value.__module__ + '.' + value.__name__} is not a default import, "
+ "add it to DEFAULT_IMPORTS in pyi_generator.py"
+ )
+
res = f"{value.__name__}[{', '.join(inner_container_type_args)}]"
if value.__name__ == "Var":
+ args = list(
+ chain.from_iterable(
+ [get_args(arg) if rx_types.is_union(arg) else [arg] for arg in args]
+ )
+ )
+
# For Var types, Union with the inner args so they can be passed directly.
types = [res] + [
_get_type_hint(arg, type_hint_globals, is_optional=False)
@@ -160,7 +184,7 @@ def _get_type_hint(value, type_hint_globals, is_optional=True) -> str:
if arg is not type(None)
]
if len(types) > 1:
- res = ", ".join(types)
+ res = ", ".join(sorted(types))
res = f"Union[{res}]"
elif isinstance(value, str):
ev = eval(value, type_hint_globals)
@@ -190,7 +214,9 @@ def _get_type_hint(value, type_hint_globals, is_optional=True) -> str:
return res
-def _generate_imports(typing_imports: Iterable[str]) -> list[ast.ImportFrom]:
+def _generate_imports(
+ typing_imports: Iterable[str],
+) -> list[ast.ImportFrom | ast.Import]:
"""Generate the import statements for the stub file.
Args:
@@ -200,22 +226,11 @@ def _generate_imports(typing_imports: Iterable[str]) -> list[ast.ImportFrom]:
The list of import statements.
"""
return [
- ast.ImportFrom(
- module="typing",
- names=[ast.alias(name=imp) for imp in sorted(typing_imports)],
- ),
- *ast.parse( # type: ignore
- textwrap.dedent(
- """
- from reflex.vars import Var, BaseVar, ComputedVar
- from reflex.event import EventChain, EventHandler, EventSpec
- from reflex.style import Style"""
- )
- ).body,
- # *[
- # ast.ImportFrom(module=name, names=[ast.alias(name=val) for val in values])
- # for name, values in EXTRA_IMPORTS.items()
- # ],
+ *[
+ ast.ImportFrom(module=name, names=[ast.alias(name=val) for val in values])
+ for name, values in DEFAULT_IMPORTS.items()
+ ],
+ ast.Import([ast.alias("reflex")]),
]
@@ -322,6 +337,7 @@ def _extract_class_props_as_ast_nodes(
all_props = []
kwargs = []
for target_class in clzs:
+ event_triggers = target_class().get_event_triggers()
# Import from the target class to ensure type hints are resolvable.
exec(f"from {target_class.__module__} import *", type_hint_globals)
for name, value in target_class.__annotations__.items():
@@ -329,6 +345,7 @@ def _extract_class_props_as_ast_nodes(
name in spec.kwonlyargs
or name in EXCLUDED_PROPS
or name in all_props
+ or name in event_triggers
or (isinstance(value, str) and "ClassVar" in value)
):
continue
@@ -358,6 +375,64 @@ def _extract_class_props_as_ast_nodes(
return kwargs
+def type_to_ast(typ, cls: type) -> ast.AST:
+ """Converts any type annotation into its AST representation.
+ Handles nested generic types, unions, etc.
+
+ Args:
+ typ: The type annotation to convert.
+ cls: The class where the type annotation is used.
+
+ Returns:
+ The AST representation of the type annotation.
+ """
+ if typ is type(None):
+ return ast.Name(id="None")
+
+ origin = get_origin(typ)
+
+ # Handle plain types (int, str, custom classes, etc.)
+ if origin is None:
+ if hasattr(typ, "__name__"):
+ if typ.__module__.startswith("reflex."):
+ typ_parts = typ.__module__.split(".")
+ cls_parts = cls.__module__.split(".")
+
+ zipped = list(zip(typ_parts, cls_parts, strict=False))
+
+ if all(a == b for a, b in zipped) and len(typ_parts) == len(cls_parts):
+ return ast.Name(id=typ.__name__)
+
+ return ast.Name(id=typ.__module__ + "." + typ.__name__)
+ return ast.Name(id=typ.__name__)
+ elif hasattr(typ, "_name"):
+ return ast.Name(id=typ._name)
+ return ast.Name(id=str(typ))
+
+ # Get the base type name (List, Dict, Optional, etc.)
+ base_name = origin._name if hasattr(origin, "_name") else origin.__name__
+
+ # Get type arguments
+ args = get_args(typ)
+
+ # Handle empty type arguments
+ if not args:
+ return ast.Name(id=base_name)
+
+ # Convert all type arguments recursively
+ arg_nodes = [type_to_ast(arg, cls) for arg in args]
+
+ # Special case for single-argument types (like List[T] or Optional[T])
+ if len(arg_nodes) == 1:
+ slice_value = arg_nodes[0]
+ else:
+ slice_value = ast.Tuple(elts=arg_nodes, ctx=ast.Load())
+
+ return ast.Subscript(
+ value=ast.Name(id=base_name), slice=ast.Index(value=slice_value), ctx=ast.Load()
+ )
+
+
def _get_parent_imports(func):
_imports = {"reflex.vars": ["Var"]}
for type_hint in inspect.get_annotations(func).values():
@@ -413,19 +488,103 @@ def _generate_component_create_functiondef(
all_props = [arg[0].arg for arg in prop_kwargs]
kwargs.extend(prop_kwargs)
+ def figure_out_return_type(annotation: Any):
+ if inspect.isclass(annotation) and issubclass(annotation, inspect._empty):
+ return ast.Name(id="EventType")
+
+ if not isinstance(annotation, str) and get_origin(annotation) is tuple:
+ arguments = get_args(annotation)
+
+ arguments_without_var = [
+ get_args(argument)[0] if get_origin(argument) == Var else argument
+ for argument in arguments
+ ]
+
+ # Convert each argument type to its AST representation
+ type_args = [type_to_ast(arg, cls=clz) for arg in arguments_without_var]
+
+ # Join the type arguments with commas for EventType
+ args_str = ", ".join(ast.unparse(arg) for arg in type_args)
+
+ # Create EventType using the joined string
+ event_type = ast.Name(id=f"EventType[{args_str}]")
+
+ return event_type
+
+ if isinstance(annotation, str) and annotation.startswith("Tuple["):
+ inside_of_tuple = annotation.removeprefix("Tuple[").removesuffix("]")
+
+ if inside_of_tuple == "()":
+ return ast.Name(id="EventType[[]]")
+
+ arguments = [""]
+
+ bracket_count = 0
+
+ for char in inside_of_tuple:
+ if char == "[":
+ bracket_count += 1
+ elif char == "]":
+ bracket_count -= 1
+
+ if char == "," and bracket_count == 0:
+ arguments.append("")
+ else:
+ arguments[-1] += char
+
+ arguments = [argument.strip() for argument in arguments]
+
+ arguments_without_var = [
+ argument.removeprefix("Var[").removesuffix("]")
+ if argument.startswith("Var[")
+ else argument
+ for argument in arguments
+ ]
+
+ return ast.Name(id=f"EventType[{', '.join(arguments_without_var)}]")
+ return ast.Name(id="EventType")
+
+ event_triggers = clz().get_event_triggers()
+
# event handler kwargs
kwargs.extend(
(
ast.arg(
arg=trigger,
- annotation=ast.Name(
- id="Optional[Union[EventHandler, EventSpec, list, function, BaseVar]]"
+ annotation=ast.Subscript(
+ ast.Name("Optional"),
+ ast.Index( # type: ignore
+ value=ast.Name(
+ id=ast.unparse(
+ figure_out_return_type(
+ inspect.signature(event_specs).return_annotation
+ )
+ if not isinstance(
+ event_specs := event_triggers[trigger], tuple
+ )
+ else ast.Subscript(
+ ast.Name("Union"),
+ ast.Tuple(
+ [
+ figure_out_return_type(
+ inspect.signature(
+ event_spec
+ ).return_annotation
+ )
+ for event_spec in event_specs
+ ]
+ ),
+ )
+ )
+ )
+ ),
),
),
ast.Constant(value=None),
)
- for trigger in sorted(clz().get_event_triggers().keys())
+ for trigger in sorted(event_triggers)
)
+
logger.debug(f"Generated {clz.__name__}.create method with {len(kwargs)} kwargs")
create_args = ast.arguments(
args=[ast.arg(arg="cls")],
@@ -436,12 +595,17 @@ def _generate_component_create_functiondef(
kwarg=ast.arg(arg="props"),
defaults=[],
)
+
definition = ast.FunctionDef(
name="create",
args=create_args,
body=[
ast.Expr(
- value=ast.Constant(value=_generate_docstrings(all_classes, all_props))
+ value=ast.Constant(
+ value=_generate_docstrings(
+ all_classes, [*all_props, *event_triggers]
+ )
+ ),
),
ast.Expr(
value=ast.Ellipsis(),
@@ -488,7 +652,11 @@ def _generate_staticmethod_call_functiondef(
kwonlyargs=[],
kw_defaults=[],
kwarg=ast.arg(arg="props"),
- defaults=[],
+ defaults=(
+ [ast.Constant(value=default) for default in fullspec.defaults]
+ if fullspec.defaults
+ else []
+ ),
)
definition = ast.FunctionDef(
name="__call__",
@@ -576,7 +744,7 @@ class StubGenerator(ast.NodeTransformer):
# Track the last class node that was visited.
self.current_class = None
# These imports will be included in the AST of stub files.
- self.typing_imports = DEFAULT_TYPING_IMPORTS
+ self.typing_imports = DEFAULT_TYPING_IMPORTS.copy()
# Whether those typing imports have been inserted yet.
self.inserted_imports = False
# Collected import statements from the module.
@@ -644,7 +812,9 @@ class StubGenerator(ast.NodeTransformer):
self.import_statements.append(ast.unparse(node))
if not self.inserted_imports:
self.inserted_imports = True
- return _generate_imports(self.typing_imports) + [node]
+ default_imports = _generate_imports(self.typing_imports)
+ self.import_statements.extend(ast.unparse(i) for i in default_imports)
+ return default_imports + [node]
return node
def visit_ImportFrom(
@@ -775,6 +945,13 @@ class StubGenerator(ast.NodeTransformer):
# Remove annotated assignments in Component classes (props)
return None
+ # remove dunder method assignments for lazy_loader.attach
+ for target in node.targets:
+ if isinstance(target, ast.Tuple):
+ for name in target.elts:
+ if isinstance(name, ast.Name) and name.id.startswith("_"):
+ return
+
return node
def visit_AnnAssign(self, node: ast.AnnAssign) -> ast.AnnAssign | None:
@@ -805,6 +982,23 @@ class StubGenerator(ast.NodeTransformer):
return node
+class InitStubGenerator(StubGenerator):
+ """A node transformer that will generate the stubs for a given init file."""
+
+ def visit_Import(
+ self, node: ast.Import | ast.ImportFrom
+ ) -> ast.Import | ast.ImportFrom | list[ast.Import | ast.ImportFrom]:
+ """Collect import statements from the init module.
+
+ Args:
+ node: The import node to visit.
+
+ Returns:
+ The modified import node(s).
+ """
+ return [node]
+
+
class PyiGenerator:
"""A .pyi file generator that will scan all defined Component in Reflex and
generate the approriate stub.
@@ -813,36 +1007,67 @@ class PyiGenerator:
modules: list = []
root: str = ""
current_module: Any = {}
+ written_files: list[str] = []
def _write_pyi_file(self, module_path: Path, source: str):
relpath = str(_relative_to_pwd(module_path)).replace("\\", "/")
- pyi_content = [
- f'"""Stub file for {relpath}"""',
- "# ------------------- DO NOT EDIT ----------------------",
- "# This file was generated by `reflex/utils/pyi_generator.py`!",
- "# ------------------------------------------------------",
- "",
- ]
- if black is not None:
- for formatted_line in black.format_file_contents(
- src_contents=source,
- fast=True,
- mode=black.mode.Mode(is_pyi=True),
- ).splitlines():
- # Bit of a hack here, since the AST cannot represent comments.
- if "def create(" in formatted_line or "Figure" in formatted_line:
- pyi_content.append(formatted_line + " # type: ignore")
- else:
- pyi_content.append(formatted_line)
- pyi_content.append("") # add empty line at the end for formatting
- else:
- pyi_content = source.splitlines()
+ pyi_content = (
+ "\n".join(
+ [
+ f'"""Stub file for {relpath}"""',
+ "# ------------------- DO NOT EDIT ----------------------",
+ "# This file was generated by `reflex/utils/pyi_generator.py`!",
+ "# ------------------------------------------------------",
+ "",
+ ]
+ )
+ + source
+ )
pyi_path = module_path.with_suffix(".pyi")
- pyi_path.write_text("\n".join(pyi_content))
+ pyi_path.write_text(pyi_content)
logger.info(f"Wrote {relpath}")
- def _scan_file(self, module_path: Path):
+ def _get_init_lazy_imports(self, mod, new_tree):
+ # retrieve the _SUBMODULES and _SUBMOD_ATTRS from an init file if present.
+ sub_mods = getattr(mod, "_SUBMODULES", None)
+ sub_mod_attrs = getattr(mod, "_SUBMOD_ATTRS", None)
+ pyright_ignore_imports = getattr(mod, "_PYRIGHT_IGNORE_IMPORTS", [])
+
+ if not sub_mods and not sub_mod_attrs:
+ return
+ sub_mods_imports = []
+ sub_mod_attrs_imports = []
+
+ if sub_mods:
+ sub_mods_imports = [
+ f"from . import {mod} as {mod}" for mod in sorted(sub_mods)
+ ]
+ sub_mods_imports.append("")
+
+ if sub_mod_attrs:
+ sub_mod_attrs = {
+ attr: mod for mod, attrs in sub_mod_attrs.items() for attr in attrs
+ }
+ # construct the import statement and handle special cases for aliases
+ sub_mod_attrs_imports = [
+ f"from .{path} import {mod if not isinstance(mod, tuple) else mod[0]} as {mod if not isinstance(mod, tuple) else mod[1]}"
+ + (
+ " # type: ignore"
+ if mod in pyright_ignore_imports
+ else " # noqa" # ignore ruff formatting here for cases like rx.list.
+ if isinstance(mod, tuple)
+ else ""
+ )
+ for mod, path in sub_mod_attrs.items()
+ ]
+ sub_mod_attrs_imports.append("")
+
+ text = "\n" + "\n".join([*sub_mods_imports, *sub_mod_attrs_imports])
+ text += ast.unparse(new_tree) + "\n"
+ return text
+
+ def _scan_file(self, module_path: Path) -> str | None:
module_import = (
_relative_to_pwd(module_path)
.with_suffix("")
@@ -860,21 +1085,34 @@ class PyiGenerator:
and obj != Component
and inspect.getmodule(obj) == module
}
- if not class_names:
+ is_init_file = _relative_to_pwd(module_path).name == "__init__.py"
+ if not class_names and not is_init_file:
return
- new_tree = StubGenerator(module, class_names).visit(
- ast.parse(inspect.getsource(module))
- )
- self._write_pyi_file(module_path, ast.unparse(new_tree))
+ if is_init_file:
+ new_tree = InitStubGenerator(module, class_names).visit(
+ ast.parse(inspect.getsource(module))
+ )
+ init_imports = self._get_init_lazy_imports(module, new_tree)
+ if not init_imports:
+ return
+ self._write_pyi_file(module_path, init_imports)
+ else:
+ new_tree = StubGenerator(module, class_names).visit(
+ ast.parse(inspect.getsource(module))
+ )
+ self._write_pyi_file(module_path, ast.unparse(new_tree))
+ return str(module_path.with_suffix(".pyi").resolve())
def _scan_files_multiprocess(self, files: list[Path]):
with Pool(processes=cpu_count()) as pool:
- pool.map(self._scan_file, files)
+ self.written_files.extend(f for f in pool.map(self._scan_file, files) if f)
def _scan_files(self, files: list[Path]):
for file in files:
- self._scan_file(file)
+ pyi_path = self._scan_file(file)
+ if pyi_path:
+ self.written_files.append(pyi_path)
def scan_all(self, targets, changed_files: list[Path] | None = None):
"""Scan all targets for class inheriting Component and generate the .pyi files.
@@ -923,15 +1161,23 @@ class PyiGenerator:
else:
self._scan_files_multiprocess(file_targets)
+ # Fix generated pyi files with ruff.
+ subprocess.run(["ruff", "format", *self.written_files])
+ subprocess.run(["ruff", "check", "--fix", *self.written_files])
-def generate_init():
- """Generate a pyi file for the main __init__.py."""
- from reflex import _MAPPING # type: ignore
+ # For some reason, we need to format the __init__.pyi files again after fixing...
+ init_files = [f for f in self.written_files if "/__init__.pyi" in f]
+ subprocess.run(["ruff", "format", *init_files])
- imports = [
- f"from {path if mod != path.rsplit('.')[-1] or mod == 'page' else '.'.join(path.rsplit('.')[:-1])} import {mod} as {mod}"
- for mod, path in _MAPPING.items()
- ]
- imports.append("")
- with contextlib.suppress(Exception):
- INIT_FILE.write_text("\n".join(imports))
+ # Post-process the generated pyi files to add hacky type: ignore comments
+ for file_path in self.written_files:
+ with FileInput(file_path, inplace=True) as f:
+ for line in f:
+ # Hack due to ast not supporting comments in the tree.
+ if (
+ "def create(" in line
+ or "Var[Figure]" in line
+ or "Var[Template]" in line
+ ):
+ line = line.rstrip() + " # type: ignore\n"
+ print(line, end="")
diff --git a/reflex/utils/redir.py b/reflex/utils/redir.py
new file mode 100644
index 000000000..1dbd989e9
--- /dev/null
+++ b/reflex/utils/redir.py
@@ -0,0 +1,52 @@
+"""Utilities to handle redirection to browser UI."""
+
+import time
+import uuid
+import webbrowser
+
+import httpx
+
+from .. import constants
+from . import console
+
+
+def open_browser_and_wait(
+ target_url: str, poll_url: str, interval: int = 2
+) -> httpx.Response:
+ """Open a browser window to target_url and request poll_url until it returns successfully.
+
+ Args:
+ target_url: The URL to open in the browser.
+ poll_url: The URL to poll for success.
+ interval: The interval in seconds to wait between polling.
+
+ Returns:
+ The response from the poll_url.
+ """
+ if not webbrowser.open(target_url):
+ console.warn(
+ f"Unable to automatically open the browser. Please navigate to {target_url} in your browser."
+ )
+ console.info("[b]Complete the workflow in the browser to continue.[/b]")
+ while True:
+ try:
+ response = httpx.get(poll_url, follow_redirects=True)
+ if response.is_success:
+ break
+ except httpx.RequestError as err:
+ console.info(f"Will retry after error occurred while polling: {err}.")
+ time.sleep(interval)
+ return response
+
+
+def reflex_build_redirect() -> str:
+ """Open the browser window to reflex.build and wait for the user to select a generation.
+
+ Returns:
+ The selected generation hash.
+ """
+ token = str(uuid.uuid4())
+ target_url = constants.Templates.REFLEX_BUILD_URL.format(reflex_init_token=token)
+ poll_url = constants.Templates.REFLEX_BUILD_POLL_URL.format(reflex_init_token=token)
+ response = open_browser_and_wait(target_url, poll_url)
+ return response.json()["generation_hash"]
diff --git a/reflex/utils/registry.py b/reflex/utils/registry.py
new file mode 100644
index 000000000..77c3d31cd
--- /dev/null
+++ b/reflex/utils/registry.py
@@ -0,0 +1,58 @@
+"""Utilities for working with registries."""
+
+import httpx
+
+from reflex.config import environment
+from reflex.utils import console, net
+
+
+def latency(registry: str) -> int:
+ """Get the latency of a registry.
+
+ Args:
+ registry (str): The URL of the registry.
+
+ Returns:
+ int: The latency of the registry in microseconds.
+ """
+ try:
+ return net.get(registry).elapsed.microseconds
+ except httpx.HTTPError:
+ console.info(f"Failed to connect to {registry}.")
+ return 10_000_000
+
+
+def average_latency(registry, attempts: int = 3) -> int:
+ """Get the average latency of a registry.
+
+ Args:
+ registry (str): The URL of the registry.
+ attempts (int): The number of attempts to make. Defaults to 10.
+
+ Returns:
+ int: The average latency of the registry in microseconds.
+ """
+ return sum(latency(registry) for _ in range(attempts)) // attempts
+
+
+def get_best_registry() -> str:
+ """Get the best registry based on latency.
+
+ Returns:
+ str: The best registry.
+ """
+ registries = [
+ "https://registry.npmjs.org",
+ "https://r.cnpmjs.org",
+ ]
+
+ return min(registries, key=average_latency)
+
+
+def _get_npm_registry() -> str:
+ """Get npm registry. If environment variable is set, use it first.
+
+ Returns:
+ str:
+ """
+ return environment.NPM_CONFIG_REGISTRY or get_best_registry()
diff --git a/reflex/utils/serializers.py b/reflex/utils/serializers.py
index 1e1de7507..614257181 100644
--- a/reflex/utils/serializers.py
+++ b/reflex/utils/serializers.py
@@ -2,30 +2,52 @@
from __future__ import annotations
+import dataclasses
+import functools
import json
-import types as builtin_types
import warnings
from datetime import date, datetime, time, timedelta
from enum import Enum
from pathlib import Path
-from typing import Any, Callable, Dict, List, Set, Tuple, Type, Union, get_type_hints
+from typing import (
+ Any,
+ Callable,
+ List,
+ Literal,
+ Optional,
+ Set,
+ Tuple,
+ Type,
+ Union,
+ get_type_hints,
+ overload,
+)
from reflex.base import Base
from reflex.constants.colors import Color, format_color
-from reflex.utils import exceptions, format, types
+from reflex.utils import types
# Mapping from type to a serializer.
# The serializer should convert the type to a JSON object.
-SerializedType = Union[str, bool, int, float, list, dict]
+SerializedType = Union[str, bool, int, float, list, dict, None]
+
+
Serializer = Callable[[Type], SerializedType]
+
+
SERIALIZERS: dict[Type, Serializer] = {}
+SERIALIZER_TYPES: dict[Type, Type] = {}
-def serializer(fn: Serializer) -> Serializer:
+def serializer(
+ fn: Serializer | None = None,
+ to: Type | None = None,
+) -> Serializer:
"""Decorator to add a serializer for a given type.
Args:
fn: The function to decorate.
+ to: The type returned by the serializer. If this is `str`, then any Var created from this type will be treated as a string.
Returns:
The decorated function.
@@ -33,8 +55,9 @@ def serializer(fn: Serializer) -> Serializer:
Raises:
ValueError: If the function does not take a single argument.
"""
- # Get the global serializers.
- global SERIALIZERS
+ if fn is None:
+ # If the function is not provided, return a partial that acts as a decorator.
+ return functools.partial(serializer, to=to) # type: ignore
# Check the type hints to get the type of the argument.
type_hints = get_type_hints(fn)
@@ -54,18 +77,44 @@ def serializer(fn: Serializer) -> Serializer:
f"Serializer for type {type_} is already registered as {registered_fn.__qualname__}."
)
+ # Apply type transformation if requested
+ if to is not None:
+ SERIALIZER_TYPES[type_] = to
+ get_serializer_type.cache_clear()
+
# Register the serializer.
SERIALIZERS[type_] = fn
+ get_serializer.cache_clear()
# Return the function.
return fn
-def serialize(value: Any) -> SerializedType | None:
+@overload
+def serialize(
+ value: Any, get_type: Literal[True]
+) -> Tuple[Optional[SerializedType], Optional[types.GenericType]]: ...
+
+
+@overload
+def serialize(value: Any, get_type: Literal[False]) -> Optional[SerializedType]: ...
+
+
+@overload
+def serialize(value: Any) -> Optional[SerializedType]: ...
+
+
+def serialize(
+ value: Any, get_type: bool = False
+) -> Union[
+ Optional[SerializedType],
+ Tuple[Optional[SerializedType], Optional[types.GenericType]],
+]:
"""Serialize the value to a JSON string.
Args:
value: The value to serialize.
+ get_type: Whether to return the type of the serialized value.
Returns:
The serialized value, or None if a serializer is not found.
@@ -75,13 +124,25 @@ def serialize(value: Any) -> SerializedType | None:
# If there is no serializer, return None.
if serializer is None:
+ if dataclasses.is_dataclass(value) and not isinstance(value, type):
+ return {k.name: getattr(value, k.name) for k in dataclasses.fields(value)}
+
+ if get_type:
+ return None, None
return None
# Serialize the value.
- return serializer(value)
+ serialized = serializer(value)
+
+ # Return the serialized value and the type.
+ if get_type:
+ return serialized, get_serializer_type(type(value))
+ else:
+ return serialized
-def get_serializer(type_: Type) -> Serializer | None:
+@functools.lru_cache
+def get_serializer(type_: Type) -> Optional[Serializer]:
"""Get the serializer for the type.
Args:
@@ -90,8 +151,6 @@ def get_serializer(type_: Type) -> Serializer | None:
Returns:
The serializer for the type, or None if there is no serializer.
"""
- global SERIALIZERS
-
# First, check if the type is registered.
serializer = SERIALIZERS.get(type_)
if serializer is not None:
@@ -106,6 +165,30 @@ def get_serializer(type_: Type) -> Serializer | None:
return None
+@functools.lru_cache
+def get_serializer_type(type_: Type) -> Optional[Type]:
+ """Get the converted type for the type after serializing.
+
+ Args:
+ type_: The type to get the serializer type for.
+
+ Returns:
+ The serialized type for the type, or None if there is no type conversion registered.
+ """
+ # First, check if the type is registered.
+ serializer = SERIALIZER_TYPES.get(type_)
+ if serializer is not None:
+ return serializer
+
+ # If the type is not registered, check if it is a subclass of a registered type.
+ for registered_type, serializer in reversed(SERIALIZER_TYPES.items()):
+ if types._issubclass(type_, registered_type):
+ return serializer
+
+ # If there is no serializer, return None.
+ return None
+
+
def has_serializer(type_: Type) -> bool:
"""Check if there is a serializer for the type.
@@ -118,7 +201,7 @@ def has_serializer(type_: Type) -> bool:
return get_serializer(type_) is not None
-@serializer
+@serializer(to=str)
def serialize_type(value: type) -> str:
"""Serialize a python type.
@@ -132,33 +215,7 @@ def serialize_type(value: type) -> str:
@serializer
-def serialize_str(value: str) -> str:
- """Serialize a string.
-
- Args:
- value: The string to serialize.
-
- Returns:
- The serialized string.
- """
- return value
-
-
-@serializer
-def serialize_primitive(value: Union[bool, int, float, None]) -> str:
- """Serialize a primitive type.
-
- Args:
- value: The number/bool/None to serialize.
-
- Returns:
- The serialized number/bool/None.
- """
- return format.json_dumps(value)
-
-
-@serializer
-def serialize_base(value: Base) -> str:
+def serialize_base(value: Base) -> dict:
"""Serialize a Base instance.
Args:
@@ -167,61 +224,23 @@ def serialize_base(value: Base) -> str:
Returns:
The serialized Base.
"""
- return value.json()
+ return {k: v for k, v in value.dict().items() if not callable(v)}
@serializer
-def serialize_list(value: Union[List, Tuple, Set]) -> str:
- """Serialize a list to a JSON string.
+def serialize_set(value: Set) -> list:
+ """Serialize a set to a JSON serializable list.
Args:
- value: The list to serialize.
+ value: The set to serialize.
Returns:
The serialized list.
"""
- # Dump the list to a string.
- fprop = format.json_dumps(list(value))
-
- # Unwrap var values.
- return format.unwrap_vars(fprop)
+ return list(value)
-@serializer
-def serialize_dict(prop: Dict[str, Any]) -> str:
- """Serialize a dictionary to a JSON string.
-
- Args:
- prop: The dictionary to serialize.
-
- Returns:
- The serialized dictionary.
-
- Raises:
- InvalidStylePropError: If the style prop is invalid.
- """
- # Import here to avoid circular imports.
- from reflex.event import EventHandler
-
- prop_dict = {}
-
- for key, value in prop.items():
- if types._issubclass(type(value), Callable):
- raise exceptions.InvalidStylePropError(
- f"The style prop `{format.to_snake_case(key)}` cannot have " # type: ignore
- f"`{value.fn.__qualname__ if isinstance(value, EventHandler) else value.__qualname__ if isinstance(value, builtin_types.FunctionType) else value}`, "
- f"an event handler or callable as its value"
- )
- prop_dict[key] = value
-
- # Dump the dict to a string.
- fprop = format.json_dumps(prop_dict)
-
- # Unwrap var values.
- return format.unwrap_vars(fprop)
-
-
-@serializer
+@serializer(to=str)
def serialize_datetime(dt: Union[date, datetime, time, timedelta]) -> str:
"""Serialize a datetime to a JSON string.
@@ -234,8 +253,8 @@ def serialize_datetime(dt: Union[date, datetime, time, timedelta]) -> str:
return str(dt)
-@serializer
-def serialize_path(path: Path):
+@serializer(to=str)
+def serialize_path(path: Path) -> str:
"""Serialize a pathlib.Path to a JSON string.
Args:
@@ -255,12 +274,12 @@ def serialize_enum(en: Enum) -> str:
en: The enum to serialize.
Returns:
- The serialized enum.
+ The serialized enum.
"""
return en.value
-@serializer
+@serializer(to=str)
def serialize_color(color: Color) -> str:
"""Serialize a color.
@@ -309,11 +328,11 @@ except ImportError:
pass
try:
- from plotly.graph_objects import Figure
+ from plotly.graph_objects import Figure, layout
from plotly.io import to_json
@serializer
- def serialize_figure(figure: Figure) -> list:
+ def serialize_figure(figure: Figure) -> dict:
"""Serialize a plotly figure.
Args:
@@ -322,7 +341,22 @@ try:
Returns:
The serialized figure.
"""
- return json.loads(str(to_json(figure)))["data"]
+ return json.loads(str(to_json(figure)))
+
+ @serializer
+ def serialize_template(template: layout.Template) -> dict:
+ """Serialize a plotly template.
+
+ Args:
+ template: The template to serialize.
+
+ Returns:
+ The serialized template.
+ """
+ return {
+ "data": json.loads(str(to_json(template.data))),
+ "layout": json.loads(str(to_json(template.layout))),
+ }
except ImportError:
pass
diff --git a/reflex/utils/telemetry.py b/reflex/utils/telemetry.py
index f7398f01a..9ae165ea2 100644
--- a/reflex/utils/telemetry.py
+++ b/reflex/utils/telemetry.py
@@ -2,8 +2,11 @@
from __future__ import annotations
+import asyncio
+import dataclasses
import multiprocessing
import platform
+import warnings
try:
from datetime import UTC, datetime
@@ -91,9 +94,7 @@ def _raise_on_missing_project_hash() -> bool:
False when compilation should be skipped (i.e. no .web directory is required).
Otherwise return True.
"""
- if should_skip_compile():
- return False
- return True
+ return not should_skip_compile()
def _prepare_event(event: str, **kwargs) -> dict:
@@ -118,7 +119,7 @@ def _prepare_event(event: str, **kwargs) -> dict:
return {}
if UTC is None:
- # for python 3.8, 3.9 & 3.10
+ # for python 3.9 & 3.10
stamp = datetime.utcnow().isoformat()
else:
# for python 3.11 & 3.12
@@ -142,7 +143,7 @@ def _prepare_event(event: str, **kwargs) -> dict:
"python_version": get_python_version(),
"cpu_count": get_cpu_count(),
"memory": get_memory(),
- "cpu_info": dict(cpuinfo) if cpuinfo else {},
+ "cpu_info": dataclasses.asdict(cpuinfo) if cpuinfo else {},
**additional_fields,
},
"timestamp": stamp,
@@ -157,17 +158,7 @@ def _send_event(event_data: dict) -> bool:
return False
-def send(event: str, telemetry_enabled: bool | None = None, **kwargs) -> bool:
- """Send anonymous telemetry for Reflex.
-
- Args:
- event: The event name.
- telemetry_enabled: Whether to send the telemetry (If None, get from config).
- kwargs: Additional data to send with the event.
-
- Returns:
- Whether the telemetry was sent successfully.
- """
+def _send(event, telemetry_enabled, **kwargs):
from reflex.config import get_config
# Get the telemetry_enabled from the config if it is not specified.
@@ -182,3 +173,37 @@ def send(event: str, telemetry_enabled: bool | None = None, **kwargs) -> bool:
if not event_data:
return False
return _send_event(event_data)
+
+
+def send(event: str, telemetry_enabled: bool | None = None, **kwargs):
+ """Send anonymous telemetry for Reflex.
+
+ Args:
+ event: The event name.
+ telemetry_enabled: Whether to send the telemetry (If None, get from config).
+ kwargs: Additional data to send with the event.
+ """
+
+ async def async_send(event, telemetry_enabled, **kwargs):
+ return _send(event, telemetry_enabled, **kwargs)
+
+ try:
+ # Within an event loop context, send the event asynchronously.
+ asyncio.create_task(async_send(event, telemetry_enabled, **kwargs))
+ except RuntimeError:
+ # If there is no event loop, send the event synchronously.
+ warnings.filterwarnings("ignore", category=RuntimeWarning)
+ _send(event, telemetry_enabled, **kwargs)
+
+
+def send_error(error: Exception, context: str):
+ """Send an error event.
+
+ Args:
+ error: The error to send.
+ context: The context of the error (e.g. "frontend" or "backend")
+
+ Returns:
+ Whether the telemetry was sent successfully.
+ """
+ return send("error", detail=type(error).__name__, context=context)
diff --git a/reflex/utils/types.py b/reflex/utils/types.py
index f75e20dcc..d58825ed5 100644
--- a/reflex/utils/types.py
+++ b/reflex/utils/types.py
@@ -3,29 +3,38 @@
from __future__ import annotations
import contextlib
+import dataclasses
import inspect
import sys
import types
-from functools import wraps
+from functools import cached_property, lru_cache, wraps
from typing import (
+ TYPE_CHECKING,
Any,
Callable,
+ ClassVar,
Dict,
Iterable,
List,
Literal,
Optional,
+ Sequence,
Tuple,
Type,
Union,
_GenericAlias, # type: ignore
get_args,
- get_origin,
get_type_hints,
)
+from typing import (
+ get_origin as get_origin_og,
+)
import sqlalchemy
+import reflex
+from reflex.components.core.breakpoints import Breakpoints
+
try:
from pydantic.v1.fields import ModelField
except ModuleNotFoundError:
@@ -42,7 +51,23 @@ from sqlalchemy.orm import (
from reflex import constants
from reflex.base import Base
-from reflex.utils import console, serializers
+from reflex.utils import console
+
+if sys.version_info >= (3, 12):
+ from typing import override as override
+else:
+
+ def override(func: Callable) -> Callable:
+ """Fallback for @override decorator.
+
+ Args:
+ func: The function to decorate.
+
+ Returns:
+ The unmodified function.
+ """
+ return func
+
# Potential GenericAlias types for isinstance checks.
GenericAliasTypes = [_GenericAlias]
@@ -73,8 +98,22 @@ PrimitiveType = Union[int, float, bool, str, list, dict, set, tuple]
StateVar = Union[PrimitiveType, Base, None]
StateIterVar = Union[list, set, tuple]
-# ArgsSpec = Callable[[Var], list[Var]]
-ArgsSpec = Callable
+if TYPE_CHECKING:
+ from reflex.vars.base import Var
+
+ # ArgsSpec = Callable[[Var], list[Var]]
+ ArgsSpec = (
+ Callable[[], Sequence[Var]]
+ | Callable[[Var], Sequence[Var]]
+ | Callable[[Var, Var], Sequence[Var]]
+ | Callable[[Var, Var, Var], Sequence[Var]]
+ | Callable[[Var, Var, Var, Var], Sequence[Var]]
+ | Callable[[Var, Var, Var, Var, Var], Sequence[Var]]
+ | Callable[[Var, Var, Var, Var, Var, Var], Sequence[Var]]
+ | Callable[[Var, Var, Var, Var, Var, Var, Var], Sequence[Var]]
+ )
+else:
+ ArgsSpec = Callable[..., List[Any]]
PrimitiveToAnnotation = {
@@ -83,6 +122,17 @@ PrimitiveToAnnotation = {
dict: Dict,
}
+RESERVED_BACKEND_VAR_NAMES = {
+ "_abc_impl",
+ "_backend_vars",
+ "_was_touched",
+}
+
+if sys.version_info >= (3, 11):
+ from typing import Self as Self
+else:
+ from typing_extensions import Self as Self
+
class Unset:
"""A class to represent an unset value.
@@ -107,6 +157,20 @@ class Unset:
return False
+@lru_cache()
+def get_origin(tp):
+ """Get the origin of a class.
+
+ Args:
+ tp: The class to get the origin of.
+
+ Returns:
+ The origin of the class.
+ """
+ return get_origin_og(tp)
+
+
+@lru_cache()
def is_generic_alias(cls: GenericType) -> bool:
"""Check whether the class is a generic alias.
@@ -119,6 +183,26 @@ def is_generic_alias(cls: GenericType) -> bool:
return isinstance(cls, GenericAliasTypes)
+def unionize(*args: GenericType) -> Type:
+ """Unionize the types.
+
+ Args:
+ args: The types to unionize.
+
+ Returns:
+ The unionized types.
+ """
+ if not args:
+ return Any
+ if len(args) == 1:
+ return args[0]
+ # We are bisecting the args list here to avoid hitting the recursion limit
+ # In Python versions >= 3.11, we can simply do `return Union[*args]`
+ midpoint = len(args) // 2
+ first_half, second_half = args[:midpoint], args[midpoint:]
+ return Union[unionize(*first_half), unionize(*second_half)]
+
+
def is_none(cls: GenericType) -> bool:
"""Check if a class is None.
@@ -131,6 +215,7 @@ def is_none(cls: GenericType) -> bool:
return cls is type(None) or cls is None
+@lru_cache()
def is_union(cls: GenericType) -> bool:
"""Check if a class is a Union.
@@ -143,6 +228,7 @@ def is_union(cls: GenericType) -> bool:
return get_origin(cls) in UnionTypes
+@lru_cache()
def is_literal(cls: GenericType) -> bool:
"""Check if a class is a Literal.
@@ -155,6 +241,27 @@ def is_literal(cls: GenericType) -> bool:
return get_origin(cls) is Literal
+def has_args(cls) -> bool:
+ """Check if the class has generic parameters.
+
+ Args:
+ cls: The class to check.
+
+ Returns:
+ Whether the class has generic
+ """
+ if get_args(cls):
+ return True
+
+ # Check if the class inherits from a generic class (using __orig_bases__)
+ if hasattr(cls, "__orig_bases__"):
+ for base in cls.__orig_bases__:
+ if get_args(base):
+ return True
+
+ return False
+
+
def is_optional(cls: GenericType) -> bool:
"""Check if a class is an Optional.
@@ -167,6 +274,20 @@ def is_optional(cls: GenericType) -> bool:
return is_union(cls) and type(None) in get_args(cls)
+def value_inside_optional(cls: GenericType) -> GenericType:
+ """Get the value inside an Optional type or the original type.
+
+ Args:
+ cls: The class to check.
+
+ Returns:
+ The value inside the Optional type or the original type.
+ """
+ if is_union(cls) and len(args := get_args(cls)) >= 2 and type(None) in args:
+ return unionize(*[arg for arg in args if arg is not type(None)])
+ return cls
+
+
def get_property_hint(attr: Any | None) -> GenericType | None:
"""Check if an attribute is a property and return its type hint.
@@ -196,10 +317,19 @@ def get_attribute_access_type(cls: GenericType, name: str) -> GenericType | None
"""
from reflex.model import Model
- attr = getattr(cls, name, None)
+ try:
+ attr = getattr(cls, name, None)
+ except NotImplementedError:
+ attr = None
+
if hint := get_property_hint(attr):
return hint
- if hasattr(cls, "__fields__") and name in cls.__fields__:
+
+ if (
+ hasattr(cls, "__fields__")
+ and name in cls.__fields__
+ and hasattr(cls.__fields__[name], "outer_type_")
+ ):
# pydantic models
field = cls.__fields__[name]
type_ = field.outer_type_
@@ -215,36 +345,41 @@ def get_attribute_access_type(cls: GenericType, name: str) -> GenericType | None
# check for list types
column = insp.columns[name]
column_type = column.type
- type_ = insp.columns[name].type.python_type
- if hasattr(column_type, "item_type") and (
- item_type := column_type.item_type.python_type # type: ignore
- ):
- if type_ in PrimitiveToAnnotation:
- type_ = PrimitiveToAnnotation[type_] # type: ignore
- type_ = type_[item_type] # type: ignore
- if column.nullable:
- type_ = Optional[type_]
- return type_
- if name not in insp.all_orm_descriptors:
- return None
- descriptor = insp.all_orm_descriptors[name]
- if hint := get_property_hint(descriptor):
- return hint
- if isinstance(descriptor, QueryableAttribute):
- prop = descriptor.property
- if not isinstance(prop, Relationship):
- return None
- type_ = prop.mapper.class_
- # TODO: check for nullable?
- type_ = List[type_] if prop.uselist else Optional[type_]
- return type_
- if isinstance(attr, AssociationProxyInstance):
- return List[
- get_attribute_access_type(
- attr.target_class,
- attr.remote_attr.key, # type: ignore[attr-defined]
- )
- ]
+ try:
+ type_ = insp.columns[name].type.python_type
+ except NotImplementedError:
+ type_ = None
+ if type_ is not None:
+ if hasattr(column_type, "item_type"):
+ try:
+ item_type = column_type.item_type.python_type # type: ignore
+ except NotImplementedError:
+ item_type = None
+ if item_type is not None:
+ if type_ in PrimitiveToAnnotation:
+ type_ = PrimitiveToAnnotation[type_] # type: ignore
+ type_ = type_[item_type] # type: ignore
+ if column.nullable:
+ type_ = Optional[type_]
+ return type_
+ if name in insp.all_orm_descriptors:
+ descriptor = insp.all_orm_descriptors[name]
+ if hint := get_property_hint(descriptor):
+ return hint
+ if isinstance(descriptor, QueryableAttribute):
+ prop = descriptor.property
+ if isinstance(prop, Relationship):
+ type_ = prop.mapper.class_
+ # TODO: check for nullable?
+ type_ = List[type_] if prop.uselist else Optional[type_]
+ return type_
+ if isinstance(attr, AssociationProxyInstance):
+ return List[
+ get_attribute_access_type(
+ attr.target_class,
+ attr.remote_attr.key, # type: ignore[attr-defined]
+ )
+ ]
elif isinstance(cls, type) and not is_generic_alias(cls) and issubclass(cls, Model):
# Check in the annotations directly (for sqlmodel.Relationship)
hints = get_type_hints(cls)
@@ -258,11 +393,9 @@ def get_attribute_access_type(cls: GenericType, name: str) -> GenericType | None
return type_
elif is_union(cls):
# Check in each arg of the annotation.
- for arg in get_args(cls):
- type_ = get_attribute_access_type(arg, name)
- if type_ is not None:
- # Return the first attribute type that is accessible.
- return type_
+ return unionize(
+ *(get_attribute_access_type(arg, name) for arg in get_args(cls))
+ )
elif isinstance(cls, type):
# Bare class
if sys.version_info >= (3, 10):
@@ -279,6 +412,7 @@ def get_attribute_access_type(cls: GenericType, name: str) -> GenericType | None
return None # Attribute is not accessible.
+@lru_cache()
def get_base_class(cls: GenericType) -> Type:
"""Get the base class of a class.
@@ -294,7 +428,7 @@ def get_base_class(cls: GenericType) -> Type:
if is_literal(cls):
# only literals of the same type are supported.
arg_type = type(get_args(cls)[0])
- if not all(type(arg) == arg_type for arg in get_args(cls)):
+ if not all(type(arg) is arg_type for arg in get_args(cls)):
raise TypeError("only literals of the same type are supported")
return type(get_args(cls)[0])
@@ -304,12 +438,44 @@ def get_base_class(cls: GenericType) -> Type:
return get_base_class(cls.__origin__) if is_generic_alias(cls) else cls
-def _issubclass(cls: GenericType, cls_check: GenericType) -> bool:
+def _breakpoints_satisfies_typing(cls_check: GenericType, instance: Any) -> bool:
+ """Check if the breakpoints instance satisfies the typing.
+
+ Args:
+ cls_check: The class to check against.
+ instance: The instance to check.
+
+ Returns:
+ Whether the breakpoints instance satisfies the typing.
+ """
+ cls_check_base = get_base_class(cls_check)
+
+ if cls_check_base == Breakpoints:
+ _, expected_type = get_args(cls_check)
+ if is_literal(expected_type):
+ for value in instance.values():
+ if not isinstance(value, str) or value not in get_args(expected_type):
+ return False
+ return True
+ elif isinstance(cls_check_base, tuple):
+ # union type, so check all types
+ return any(
+ _breakpoints_satisfies_typing(type_to_check, instance)
+ for type_to_check in get_args(cls_check)
+ )
+ elif cls_check_base == reflex.vars.Var and "__args__" in cls_check.__dict__:
+ return _breakpoints_satisfies_typing(get_args(cls_check)[0], instance)
+
+ return False
+
+
+def _issubclass(cls: GenericType, cls_check: GenericType, instance: Any = None) -> bool:
"""Check if a class is a subclass of another class.
Args:
cls: The class to check.
cls_check: The class to check against.
+ instance: An instance of cls to aid in checking generics.
Returns:
Whether the class is a subclass of the other class.
@@ -331,6 +497,10 @@ def _issubclass(cls: GenericType, cls_check: GenericType) -> bool:
if isinstance(cls_base, tuple):
return False
+ # Check that fields of breakpoints match the expected values.
+ if isinstance(instance, Breakpoints):
+ return _breakpoints_satisfies_typing(cls_check, instance)
+
# Check if the types match.
try:
return cls_check_base == Any or issubclass(cls_base, cls_check_base)
@@ -340,16 +510,66 @@ def _issubclass(cls: GenericType, cls_check: GenericType) -> bool:
raise TypeError(f"Invalid type for issubclass: {cls_base}") from te
-def _isinstance(obj: Any, cls: GenericType) -> bool:
+def _isinstance(obj: Any, cls: GenericType, nested: bool = False) -> bool:
"""Check if an object is an instance of a class.
Args:
obj: The object to check.
cls: The class to check against.
+ nested: Whether the check is nested.
Returns:
Whether the object is an instance of the class.
"""
+ if cls is Any:
+ return True
+
+ if cls is None or cls is type(None):
+ return obj is None
+
+ if is_literal(cls):
+ return obj in get_args(cls)
+
+ if is_union(cls):
+ return any(_isinstance(obj, arg) for arg in get_args(cls))
+
+ origin = get_origin(cls)
+
+ if origin is None:
+ # cls is a simple class
+ return isinstance(obj, cls)
+
+ args = get_args(cls)
+
+ if not args:
+ # cls is a simple generic class
+ return isinstance(obj, origin)
+
+ if nested and args:
+ if origin is list:
+ return isinstance(obj, list) and all(
+ _isinstance(item, args[0]) for item in obj
+ )
+ if origin is tuple:
+ if args[-1] is Ellipsis:
+ return isinstance(obj, tuple) and all(
+ _isinstance(item, args[0]) for item in obj
+ )
+ return (
+ isinstance(obj, tuple)
+ and len(obj) == len(args)
+ and all(_isinstance(item, arg) for item, arg in zip(obj, args))
+ )
+ if origin is dict:
+ return isinstance(obj, dict) and all(
+ _isinstance(key, args[0]) and _isinstance(value, args[1])
+ for key, value in obj.items()
+ )
+ if origin is set:
+ return isinstance(obj, set) and all(
+ _isinstance(item, args[0]) for item in obj
+ )
+
return isinstance(obj, get_base_class(cls))
@@ -376,12 +596,18 @@ def is_valid_var_type(type_: Type) -> bool:
Returns:
Whether the type is a valid prop type.
"""
+ from reflex.utils import serializers
+
if is_union(type_):
return all((is_valid_var_type(arg) for arg in get_args(type_)))
- return _issubclass(type_, StateVar) or serializers.has_serializer(type_)
+ return (
+ _issubclass(type_, StateVar)
+ or serializers.has_serializer(type_)
+ or dataclasses.is_dataclass(type_)
+ )
-def is_backend_variable(name: str, cls: Type | None = None) -> bool:
+def is_backend_base_variable(name: str, cls: Type) -> bool:
"""Check if this variable name correspond to a backend variable.
Args:
@@ -391,9 +617,51 @@ def is_backend_variable(name: str, cls: Type | None = None) -> bool:
Returns:
bool: The result of the check
"""
- if cls is not None and name.startswith(f"_{cls.__name__}__"):
+ if name in RESERVED_BACKEND_VAR_NAMES:
return False
- return name.startswith("_") and not name.startswith("__")
+
+ if not name.startswith("_"):
+ return False
+
+ if name.startswith("__"):
+ return False
+
+ if name.startswith(f"_{cls.__name__}__"):
+ return False
+
+ # Extract the namespace of the original module if defined (dynamic substates).
+ if callable(getattr(cls, "_get_type_hints", None)):
+ hints = cls._get_type_hints()
+ else:
+ hints = get_type_hints(cls)
+ if name in hints:
+ hint = get_origin(hints[name])
+ if hint == ClassVar:
+ return False
+
+ if name in cls.inherited_backend_vars:
+ return False
+
+ from reflex.vars.base import is_computed_var
+
+ if name in cls.__dict__:
+ value = cls.__dict__[name]
+ if type(value) is classmethod:
+ return False
+ if callable(value):
+ return False
+
+ if isinstance(
+ value,
+ (
+ types.FunctionType,
+ property,
+ cached_property,
+ ),
+ ) or is_computed_var(value):
+ return False
+
+ return True
def check_type_in_allowed_types(value_type: Type, allowed_types: Iterable) -> bool:
@@ -487,7 +755,7 @@ def validate_parameter_literals(func):
annotations = {param[0]: param[1].annotation for param in func_params}
# validate args
- for param, arg in zip(annotations.keys(), args):
+ for param, arg in zip(annotations, args):
if annotations[param] is inspect.Parameter.empty:
continue
validate_literal(param, arg, annotations[param], func.__name__)
@@ -506,3 +774,69 @@ def validate_parameter_literals(func):
# Store this here for performance.
StateBases = get_base_class(StateVar)
StateIterBases = get_base_class(StateIterVar)
+
+
+def typehint_issubclass(possible_subclass: Any, possible_superclass: Any) -> bool:
+ """Check if a type hint is a subclass of another type hint.
+
+ Args:
+ possible_subclass: The type hint to check.
+ possible_superclass: The type hint to check against.
+
+ Returns:
+ Whether the type hint is a subclass of the other type hint.
+ """
+ if possible_superclass is Any:
+ return True
+ if possible_subclass is Any:
+ return False
+
+ provided_type_origin = get_origin(possible_subclass)
+ accepted_type_origin = get_origin(possible_superclass)
+
+ if provided_type_origin is None and accepted_type_origin is None:
+ # In this case, we are dealing with a non-generic type, so we can use issubclass
+ return issubclass(possible_subclass, possible_superclass)
+
+ # Remove this check when Python 3.10 is the minimum supported version
+ if hasattr(types, "UnionType"):
+ provided_type_origin = (
+ Union if provided_type_origin is types.UnionType else provided_type_origin
+ )
+ accepted_type_origin = (
+ Union if accepted_type_origin is types.UnionType else accepted_type_origin
+ )
+
+ # Get type arguments (e.g., [float, int] for Dict[float, int])
+ provided_args = get_args(possible_subclass)
+ accepted_args = get_args(possible_superclass)
+
+ if accepted_type_origin is Union:
+ if provided_type_origin is not Union:
+ return any(
+ typehint_issubclass(possible_subclass, accepted_arg)
+ for accepted_arg in accepted_args
+ )
+ return all(
+ any(
+ typehint_issubclass(provided_arg, accepted_arg)
+ for accepted_arg in accepted_args
+ )
+ for provided_arg in provided_args
+ )
+
+ # Check if the origin of both types is the same (e.g., list for List[int])
+ # This probably should be issubclass instead of ==
+ if (provided_type_origin or possible_subclass) != (
+ accepted_type_origin or possible_superclass
+ ):
+ return False
+
+ # Ensure all specific types are compatible with accepted types
+ # Note this is not necessarily correct, as it doesn't check against contravariance and covariance
+ # It also ignores when the length of the arguments is different
+ return all(
+ typehint_issubclass(provided_arg, accepted_arg)
+ for provided_arg, accepted_arg in zip(provided_args, accepted_args)
+ if accepted_arg is not Any
+ )
diff --git a/reflex/utils/watch.py b/reflex/utils/watch.py
deleted file mode 100644
index a56635d6e..000000000
--- a/reflex/utils/watch.py
+++ /dev/null
@@ -1,94 +0,0 @@
-"""General utility functions."""
-
-import contextlib
-import os
-import shutil
-import time
-
-from watchdog.events import FileSystemEvent, FileSystemEventHandler
-from watchdog.observers import Observer
-
-from reflex.constants import Dirs
-
-
-class AssetFolderWatch:
- """Asset folder watch class."""
-
- def __init__(self, root):
- """Initialize the Watch Class.
-
- Args:
- root: root path of the public.
- """
- self.path = str(root / Dirs.APP_ASSETS)
- self.event_handler = AssetFolderHandler(root)
-
- def start(self):
- """Start watching asset folder."""
- self.observer = Observer()
- self.observer.schedule(self.event_handler, self.path, recursive=True)
- self.observer.start()
-
-
-class AssetFolderHandler(FileSystemEventHandler):
- """Asset folder event handler."""
-
- def __init__(self, root):
- """Initialize the AssetFolderHandler Class.
-
- Args:
- root: root path of the public.
- """
- super().__init__()
- self.root = root
-
- def on_modified(self, event: FileSystemEvent):
- """Event handler when a file or folder was modified.
-
- This is called every time after a file is created, modified and deleted.
-
- Args:
- event: Event information.
- """
- dest_path = self.get_dest_path(event.src_path)
-
- # wait 1 sec for fully saved
- time.sleep(1)
-
- if os.path.isfile(event.src_path):
- with contextlib.suppress(PermissionError):
- shutil.copyfile(event.src_path, dest_path)
- if os.path.isdir(event.src_path):
- if os.path.exists(dest_path):
- shutil.rmtree(dest_path)
- with contextlib.suppress(PermissionError):
- shutil.copytree(event.src_path, dest_path)
-
- def on_deleted(self, event: FileSystemEvent):
- """Event hander when a file or folder was deleted.
-
- Args:
- event: Event infomation.
- """
- dest_path = self.get_dest_path(event.src_path)
-
- if os.path.isfile(dest_path):
- # when event is about a file, pass
- # this will be deleted at on_modified function
- return
-
- if os.path.exists(dest_path):
- shutil.rmtree(dest_path)
-
- def get_dest_path(self, src_path: str) -> str:
- """Get public file path.
-
- Args:
- src_path: The asset file path.
-
- Returns:
- The public file path.
- """
- return src_path.replace(
- str(self.root / Dirs.APP_ASSETS), str(self.root / Dirs.WEB_ASSETS)
- )
diff --git a/reflex/vars.py b/reflex/vars.py
deleted file mode 100644
index 6ac78706a..000000000
--- a/reflex/vars.py
+++ /dev/null
@@ -1,2103 +0,0 @@
-"""Define a state var."""
-
-from __future__ import annotations
-
-import contextlib
-import dataclasses
-import dis
-import functools
-import inspect
-import json
-import random
-import re
-import string
-import sys
-from types import CodeType, FunctionType
-from typing import (
- TYPE_CHECKING,
- Any,
- Callable,
- Dict,
- Iterable,
- List,
- Literal,
- Optional,
- Tuple,
- Type,
- Union,
- _GenericAlias, # type: ignore
- cast,
- get_args,
- get_origin,
- get_type_hints,
-)
-
-from reflex import constants
-from reflex.base import Base
-from reflex.utils import console, format, imports, serializers, types
-from reflex.utils.exceptions import VarAttributeError, VarTypeError, VarValueError
-
-# This module used to export ImportVar itself, so we still import it for export here
-from reflex.utils.imports import ImportDict, ImportVar
-
-if TYPE_CHECKING:
- from reflex.state import BaseState
-
-# Set of unique variable names.
-USED_VARIABLES = set()
-
-# Supported operators for all types.
-ALL_OPS = ["==", "!=", "!==", "===", "&&", "||"]
-# Delimiters used between function args or operands.
-DELIMITERS = [","]
-# Mapping of valid operations for different type combinations.
-OPERATION_MAPPING = {
- (int, int): {
- "+",
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "&",
- },
- (int, str): {"*"},
- (int, list): {"*"},
- (str, str): {"+", ">", "<", "<=", ">="},
- (float, float): {"+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="},
- (float, int): {"+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="},
- (list, list): {"+", ">", "<", "<=", ">="},
-}
-
-# These names were changed in reflex 0.3.0
-REPLACED_NAMES = {
- "full_name": "_var_full_name",
- "name": "_var_name",
- "state": "_var_data.state",
- "type_": "_var_type",
- "is_local": "_var_is_local",
- "is_string": "_var_is_string",
- "set_state": "_var_set_state",
- "deps": "_deps",
-}
-
-PYTHON_JS_TYPE_MAP = {
- (int, float): "number",
- (str,): "string",
- (bool,): "boolean",
- (list, tuple): "Array",
- (dict,): "Object",
- (None,): "null",
-}
-
-
-def get_unique_variable_name() -> str:
- """Get a unique variable name.
-
- Returns:
- The unique variable name.
- """
- name = "".join([random.choice(string.ascii_lowercase) for _ in range(8)])
- if name not in USED_VARIABLES:
- USED_VARIABLES.add(name)
- return name
- return get_unique_variable_name()
-
-
-class VarData(Base):
- """Metadata associated with a Var."""
-
- # The name of the enclosing state.
- state: str = ""
-
- # Imports needed to render this var
- imports: ImportDict = {}
-
- # Hooks that need to be present in the component to render this var
- hooks: Dict[str, None] = {}
-
- # Positions of interpolated strings. This is used by the decoder to figure
- # out where the interpolations are and only escape the non-interpolated
- # segments.
- interpolations: List[Tuple[int, int]] = []
-
- @classmethod
- def merge(cls, *others: VarData | None) -> VarData | None:
- """Merge multiple var data objects.
-
- Args:
- *others: The var data objects to merge.
-
- Returns:
- The merged var data object.
- """
- state = ""
- _imports = {}
- hooks = {}
- interpolations = []
- for var_data in others:
- if var_data is None:
- continue
- state = state or var_data.state
- _imports = imports.merge_imports(_imports, var_data.imports)
- hooks.update(var_data.hooks)
- interpolations += var_data.interpolations
-
- return (
- cls(
- state=state,
- imports=_imports,
- hooks=hooks,
- interpolations=interpolations,
- )
- or None
- )
-
- def __bool__(self) -> bool:
- """Check if the var data is non-empty.
-
- Returns:
- True if any field is set to a non-default value.
- """
- return bool(self.state or self.imports or self.hooks or self.interpolations)
-
- def __eq__(self, other: Any) -> bool:
- """Check if two var data objects are equal.
-
- Args:
- other: The other var data object to compare.
-
- Returns:
- True if all fields are equal and collapsed imports are equal.
- """
- if not isinstance(other, VarData):
- return False
-
- # Don't compare interpolations - that's added in by the decoder, and
- # not part of the vardata itself.
- return (
- self.state == other.state
- and self.hooks.keys() == other.hooks.keys()
- and imports.collapse_imports(self.imports)
- == imports.collapse_imports(other.imports)
- )
-
- def dict(self) -> dict:
- """Convert the var data to a dictionary.
-
- Returns:
- The var data dictionary.
- """
- return {
- "state": self.state,
- "interpolations": list(self.interpolations),
- "imports": {
- lib: [import_var.dict() for import_var in import_vars]
- for lib, import_vars in self.imports.items()
- },
- "hooks": self.hooks,
- }
-
-
-def _encode_var(value: Var) -> str:
- """Encode the state name into a formatted var.
-
- Args:
- value: The value to encode the state name into.
-
- Returns:
- The encoded var.
- """
- if value._var_data:
- from reflex.utils.serializers import serialize
-
- final_value = str(value)
- data = value._var_data.dict()
- data["string_length"] = len(final_value)
- data_json = value._var_data.__config__.json_dumps(data, default=serialize)
-
- return (
- f"{constants.REFLEX_VAR_OPENING_TAG}{data_json}{constants.REFLEX_VAR_CLOSING_TAG}"
- + final_value
- )
-
- return str(value)
-
-
-# Compile regex for finding reflex var tags.
-_decode_var_pattern_re = (
- rf"{constants.REFLEX_VAR_OPENING_TAG}(.*?){constants.REFLEX_VAR_CLOSING_TAG}"
-)
-_decode_var_pattern = re.compile(_decode_var_pattern_re, flags=re.DOTALL)
-
-
-def _decode_var(value: str) -> tuple[VarData | None, str]:
- """Decode the state name from a formatted var.
-
- Args:
- value: The value to extract the state name from.
-
- Returns:
- The extracted state name and the value without the state name.
- """
- var_datas = []
- if isinstance(value, str):
- # fast path if there is no encoded VarData
- if constants.REFLEX_VAR_OPENING_TAG not in value:
- return None, value
-
- offset = 0
-
- # Initialize some methods for reading json.
- var_data_config = VarData().__config__
-
- def json_loads(s):
- try:
- return var_data_config.json_loads(s)
- except json.decoder.JSONDecodeError:
- return var_data_config.json_loads(var_data_config.json_loads(f'"{s}"'))
-
- # Find all tags.
- while m := _decode_var_pattern.search(value):
- start, end = m.span()
- value = value[:start] + value[end:]
-
- # Read the JSON, pull out the string length, parse the rest as VarData.
- data = json_loads(m.group(1))
- string_length = data.pop("string_length", None)
- var_data = VarData.parse_obj(data)
-
- # Use string length to compute positions of interpolations.
- if string_length is not None:
- realstart = start + offset
- var_data.interpolations = [(realstart, realstart + string_length)]
-
- var_datas.append(var_data)
- offset += end - start
-
- return VarData.merge(*var_datas) if var_datas else None, value
-
-
-def _extract_var_data(value: Iterable) -> list[VarData | None]:
- """Extract the var imports and hooks from an iterable containing a Var.
-
- Args:
- value: The iterable to extract the VarData from
-
- Returns:
- The extracted VarDatas.
- """
- from reflex.style import Style
-
- var_datas = []
- with contextlib.suppress(TypeError):
- for sub in value:
- if isinstance(sub, Var):
- var_datas.append(sub._var_data)
- elif not isinstance(sub, str):
- # Recurse into dict values.
- if hasattr(sub, "values") and callable(sub.values):
- var_datas.extend(_extract_var_data(sub.values()))
- # Recurse into iterable values (or dict keys).
- var_datas.extend(_extract_var_data(sub))
-
- # Style objects should already have _var_data.
- if isinstance(value, Style):
- var_datas.append(value._var_data)
- else:
- # Recurse when value is a dict itself.
- values = getattr(value, "values", None)
- if callable(values):
- var_datas.extend(_extract_var_data(values()))
- return var_datas
-
-
-class Var:
- """An abstract var."""
-
- # The name of the var.
- _var_name: str
-
- # The type of the var.
- _var_type: Type
-
- # Whether this is a local javascript variable.
- _var_is_local: bool
-
- # Whether the var is a string literal.
- _var_is_string: bool
-
- # _var_full_name should be prefixed with _var_state
- _var_full_name_needs_state_prefix: bool
-
- # Extra metadata associated with the Var
- _var_data: Optional[VarData]
-
- @classmethod
- def create(
- cls, value: Any, _var_is_local: bool = True, _var_is_string: bool = False
- ) -> Var | None:
- """Create a var from a value.
-
- Args:
- value: The value to create the var from.
- _var_is_local: Whether the var is local.
- _var_is_string: Whether the var is a string literal.
-
- Returns:
- The var.
-
- Raises:
- VarTypeError: If the value is JSON-unserializable.
- """
- # Check for none values.
- if value is None:
- return None
-
- # If the value is already a var, do nothing.
- if isinstance(value, Var):
- return value
-
- # Try to pull the imports and hooks from contained values.
- _var_data = None
- if not isinstance(value, str):
- _var_data = VarData.merge(*_extract_var_data(value))
-
- # Try to serialize the value.
- type_ = type(value)
- name = value if type_ in types.JSONType else serializers.serialize(value)
- if name is None:
- raise VarTypeError(
- f"No JSON serializer found for var {value} of type {type_}."
- )
- name = name if isinstance(name, str) else format.json_dumps(name)
-
- return BaseVar(
- _var_name=name,
- _var_type=type_,
- _var_is_local=_var_is_local,
- _var_is_string=_var_is_string,
- _var_data=_var_data,
- )
-
- @classmethod
- def create_safe(
- cls, value: Any, _var_is_local: bool = True, _var_is_string: bool = False
- ) -> Var:
- """Create a var from a value, asserting that it is not None.
-
- Args:
- value: The value to create the var from.
- _var_is_local: Whether the var is local.
- _var_is_string: Whether the var is a string literal.
-
- Returns:
- The var.
- """
- var = cls.create(
- value,
- _var_is_local=_var_is_local,
- _var_is_string=_var_is_string,
- )
- assert var is not None
- return var
-
- @classmethod
- def __class_getitem__(cls, type_: str) -> _GenericAlias:
- """Get a typed var.
-
- Args:
- type_: The type of the var.
-
- Returns:
- The var class item.
- """
- return _GenericAlias(cls, type_)
-
- def __post_init__(self) -> None:
- """Post-initialize the var."""
- # Decode any inline Var markup and apply it to the instance
- _var_data, _var_name = _decode_var(self._var_name)
- if _var_data:
- self._var_name = _var_name
- self._var_data = VarData.merge(self._var_data, _var_data)
-
- def _replace(self, merge_var_data=None, **kwargs: Any) -> Var:
- """Make a copy of this Var with updated fields.
-
- Args:
- merge_var_data: VarData to merge into the existing VarData.
- **kwargs: Var fields to update.
-
- Returns:
- A new BaseVar with the updated fields overwriting the corresponding fields in this Var.
- """
- field_values = dict(
- _var_name=kwargs.pop("_var_name", self._var_name),
- _var_type=kwargs.pop("_var_type", self._var_type),
- _var_is_local=kwargs.pop("_var_is_local", self._var_is_local),
- _var_is_string=kwargs.pop("_var_is_string", self._var_is_string),
- _var_full_name_needs_state_prefix=kwargs.pop(
- "_var_full_name_needs_state_prefix",
- self._var_full_name_needs_state_prefix,
- ),
- _var_data=VarData.merge(
- kwargs.get("_var_data", self._var_data), merge_var_data
- ),
- )
- return BaseVar(**field_values)
-
- def _decode(self) -> Any:
- """Decode Var as a python value.
-
- Note that Var with state set cannot be decoded python-side and will be
- returned as full_name.
-
- Returns:
- The decoded value or the Var name.
- """
- if self._var_is_string:
- return self._var_name
- try:
- return json.loads(self._var_name)
- except ValueError:
- return self._var_name
-
- def equals(self, other: Var) -> bool:
- """Check if two vars are equal.
-
- Args:
- other: The other var to compare.
-
- Returns:
- Whether the vars are equal.
- """
- return (
- self._var_name == other._var_name
- and self._var_type == other._var_type
- and self._var_is_local == other._var_is_local
- and self._var_full_name_needs_state_prefix
- == other._var_full_name_needs_state_prefix
- and self._var_data == other._var_data
- )
-
- def _merge(self, other) -> Var:
- """Merge two or more dicts.
-
- Args:
- other: The other var to merge.
-
- Returns:
- The merged var.
- """
- if other is None:
- return self._replace()
- if not isinstance(other, Var):
- other = Var.create(other)
- return self._replace(
- _var_name=f"{{...{self._var_name}, ...{other._var_name}}}" # type: ignore
- )
-
- def to_string(self, json: bool = True) -> Var:
- """Convert a var to a string.
-
- Args:
- json: Whether to convert to a JSON string.
-
- Returns:
- The stringified var.
- """
- fn = "JSON.stringify" if json else "String"
- return self.operation(fn=fn, type_=str)
-
- def __hash__(self) -> int:
- """Define a hash function for a var.
-
- Returns:
- The hash of the var.
- """
- return hash((self._var_name, str(self._var_type)))
-
- def __str__(self) -> str:
- """Wrap the var so it can be used in templates.
-
- Returns:
- The wrapped var, i.e. {state.var}.
- """
- out = (
- self._var_full_name
- if self._var_is_local
- else format.wrap(self._var_full_name, "{")
- )
- if self._var_is_string:
- out = format.format_string(out)
- return out
-
- def __bool__(self) -> bool:
- """Raise exception if using Var in a boolean context.
-
- Raises:
- VarTypeError: when attempting to bool-ify the Var.
- """
- raise VarTypeError(
- f"Cannot convert Var {self._var_full_name!r} to bool for use with `if`, `and`, `or`, and `not`. "
- "Instead use `rx.cond` and bitwise operators `&` (and), `|` (or), `~` (invert)."
- )
-
- def __iter__(self) -> Any:
- """Raise exception if using Var in an iterable context.
-
- Raises:
- VarTypeError: when attempting to iterate over the Var.
- """
- raise VarTypeError(
- f"Cannot iterate over Var {self._var_full_name!r}. Instead use `rx.foreach`."
- )
-
- def __format__(self, format_spec: str) -> str:
- """Format the var into a Javascript equivalent to an f-string.
-
- Args:
- format_spec: The format specifier (Ignored for now).
-
- Returns:
- The formatted var.
- """
- # Encode the _var_data into the formatted output for tracking purposes.
- str_self = _encode_var(self)
- if self._var_is_local:
- return str_self
- return f"${str_self}"
-
- def __getitem__(self, i: Any) -> Var:
- """Index into a var.
-
- Args:
- i: The index to index into.
-
- Returns:
- The indexed var.
-
- Raises:
- VarTypeError: If the var is not indexable.
- """
- # Indexing is only supported for strings, lists, tuples, dicts, and dataframes.
- if not (
- types._issubclass(self._var_type, Union[List, Dict, Tuple, str])
- or types.is_dataframe(self._var_type)
- ):
- if self._var_type == Any:
- raise VarTypeError(
- "Could not index into var of type Any. (If you are trying to index into a state var, "
- "add the correct type annotation to the var.)"
- )
- raise VarTypeError(
- f"Var {self._var_name} of type {self._var_type} does not support indexing."
- )
-
- # The type of the indexed var.
- type_ = Any
-
- # Convert any vars to local vars.
- if isinstance(i, Var):
- i = i._replace(_var_is_local=True)
-
- # Handle list/tuple/str indexing.
- if types._issubclass(self._var_type, Union[List, Tuple, str]):
- # List/Tuple/String indices must be ints, slices, or vars.
- if (
- not isinstance(i, types.get_args(Union[int, slice, Var]))
- or isinstance(i, Var)
- and not i._var_type == int
- ):
- raise VarTypeError("Index must be an integer or an integer var.")
-
- # Handle slices first.
- if isinstance(i, slice):
- # Get the start and stop indices.
- start = i.start or 0
- stop = i.stop or "undefined"
-
- # Use the slice function.
- return self._replace(
- _var_name=f"{self._var_name}.slice({start}, {stop})",
- _var_is_string=False,
- )
-
- # Get the type of the indexed var.
- if types.is_generic_alias(self._var_type):
- index = i if not isinstance(i, Var) else 0
- type_ = types.get_args(self._var_type)
- type_ = type_[index % len(type_)] if type_ else Any
- elif types._issubclass(self._var_type, str):
- type_ = str
-
- # Use `at` to support negative indices.
- return self._replace(
- _var_name=f"{self._var_name}.at({i})",
- _var_type=type_,
- _var_is_string=False,
- )
-
- # Dictionary / dataframe indexing.
- # Tuples are currently not supported as indexes.
- if (
- (
- types._issubclass(self._var_type, Dict)
- or types.is_dataframe(self._var_type)
- )
- and not isinstance(i, types.get_args(Union[int, str, float, Var]))
- ) or (
- isinstance(i, Var)
- and not types._issubclass(
- i._var_type, types.get_args(Union[int, str, float])
- )
- ):
- raise VarTypeError(
- "Index must be one of the following types: int, str, int or str Var"
- )
- # Get the type of the indexed var.
- if isinstance(i, str):
- i = format.wrap(i, '"')
- type_ = (
- types.get_args(self._var_type)[1]
- if types.is_generic_alias(self._var_type)
- else Any
- )
-
- # Use normal indexing here.
- return self._replace(
- _var_name=f"{self._var_name}[{i}]",
- _var_type=type_,
- _var_is_string=False,
- )
-
- def __getattribute__(self, name: str) -> Any:
- """Get a var attribute.
-
- Args:
- name: The name of the attribute.
-
- Returns:
- The var attribute.
-
- Raises:
- VarAttributeError: If the attribute cannot be found, or if __getattr__ fallback should be used.
- """
- try:
- var_attribute = super().__getattribute__(name)
- if not name.startswith("_"):
- # Check if the attribute should be accessed through the Var instead of
- # accessing one of the Var operations
- type_ = types.get_attribute_access_type(
- super().__getattribute__("_var_type"), name
- )
- if type_ is not None:
- raise VarAttributeError(
- f"{name} is being accessed through the Var."
- )
- # Return the attribute as-is.
- return var_attribute
- except VarAttributeError:
- raise # fall back to __getattr__ anyway
-
- def __getattr__(self, name: str) -> Var:
- """Get a var attribute.
-
- Args:
- name: The name of the attribute.
-
- Returns:
- The var attribute.
-
- Raises:
- VarAttributeError: If the var is wrongly annotated or can't find attribute.
- VarTypeError: If an annotation to the var isn't provided.
- """
- # Check if the attribute is one of the class fields.
- if not name.startswith("_"):
- if self._var_type == Any:
- raise VarTypeError(
- f"You must provide an annotation for the state var `{self._var_full_name}`. Annotation cannot be `{self._var_type}`"
- ) from None
- is_optional = types.is_optional(self._var_type)
- type_ = types.get_attribute_access_type(self._var_type, name)
-
- if type_ is not None:
- return self._replace(
- _var_name=f"{self._var_name}{'?' if is_optional else ''}.{name}",
- _var_type=type_,
- _var_is_string=False,
- )
-
- if name in REPLACED_NAMES:
- raise VarAttributeError(
- f"Field {name!r} was renamed to {REPLACED_NAMES[name]!r}"
- )
-
- raise VarAttributeError(
- f"The State var `{self._var_full_name}` has no attribute '{name}' or may have been annotated "
- f"wrongly."
- )
-
- raise VarAttributeError(
- f"The State var has no attribute '{name}' or may have been annotated wrongly.",
- )
-
- def operation(
- self,
- op: str = "",
- other: Var | None = None,
- type_: Type | None = None,
- flip: bool = False,
- fn: str | None = None,
- invoke_fn: bool = False,
- ) -> Var:
- """Perform an operation on a var.
-
- Args:
- op: The operation to perform.
- other: The other var to perform the operation on.
- type_: The type of the operation result.
- flip: Whether to flip the order of the operation.
- fn: A function to apply to the operation.
- invoke_fn: Whether to invoke the function.
-
- Returns:
- The operation result.
-
- Raises:
- VarTypeError: If the operation between two operands is invalid.
- VarValueError: If flip is set to true and value of operand is not provided
- """
- if isinstance(other, str):
- other = Var.create(json.dumps(other))
- else:
- other = Var.create(other)
-
- type_ = type_ or self._var_type
-
- if other is None and flip:
- raise VarValueError(
- "flip_operands cannot be set to True if the value of 'other' operand is not provided"
- )
-
- left_operand, right_operand = (other, self) if flip else (self, other)
-
- def get_operand_full_name(operand):
- # operand vars that are string literals need to be wrapped in back ticks.
- return (
- operand._var_name_unwrapped
- if operand._var_is_string
- and not operand._var_state
- and operand._var_is_local
- else operand._var_full_name
- )
-
- if other is not None:
- # check if the operation between operands is valid.
- if op and not self.is_valid_operation(
- types.get_base_class(left_operand._var_type), # type: ignore
- types.get_base_class(right_operand._var_type), # type: ignore
- op,
- ):
- raise VarTypeError(
- f"Unsupported Operand type(s) for {op}: `{left_operand._var_full_name}` of type {left_operand._var_type.__name__} and `{right_operand._var_full_name}` of type {right_operand._var_type.__name__}" # type: ignore
- )
-
- left_operand_full_name = get_operand_full_name(left_operand)
- right_operand_full_name = get_operand_full_name(right_operand)
-
- left_operand_full_name = format.wrap(left_operand_full_name, "(")
- right_operand_full_name = format.wrap(right_operand_full_name, "(")
-
- # apply function to operands
- if fn is not None:
- if invoke_fn:
- # invoke the function on left operand.
- operation_name = (
- f"{left_operand_full_name}.{fn}({right_operand_full_name})"
- ) # type: ignore
- else:
- # pass the operands as arguments to the function.
- operation_name = (
- f"{left_operand_full_name} {op} {right_operand_full_name}"
- ) # type: ignore
- operation_name = f"{fn}({operation_name})"
- else:
- # apply operator to operands (left operand right_operand)
- operation_name = (
- f"{left_operand_full_name} {op} {right_operand_full_name}"
- ) # type: ignore
- operation_name = format.wrap(operation_name, "(")
- else:
- # apply operator to left operand ( left_operand)
- operation_name = f"{op}{get_operand_full_name(self)}"
- # apply function to operands
- if fn is not None:
- operation_name = (
- f"{fn}({operation_name})"
- if not invoke_fn
- else f"{get_operand_full_name(self)}.{fn}()"
- )
-
- return self._replace(
- _var_name=operation_name,
- _var_type=type_,
- _var_is_string=False,
- _var_full_name_needs_state_prefix=False,
- merge_var_data=other._var_data if other is not None else None,
- )
-
- @staticmethod
- def is_valid_operation(
- operand1_type: Type, operand2_type: Type, operator: str
- ) -> bool:
- """Check if an operation between two operands is valid.
-
- Args:
- operand1_type: Type of the operand
- operand2_type: Type of the second operand
- operator: The operator.
-
- Returns:
- Whether operation is valid or not
-
- """
- if operator in ALL_OPS or operator in DELIMITERS:
- return True
-
- # bools are subclasses of ints
- pair = tuple(
- sorted(
- [
- int if operand1_type == bool else operand1_type,
- int if operand2_type == bool else operand2_type,
- ],
- key=lambda x: x.__name__,
- )
- )
- return pair in OPERATION_MAPPING and operator in OPERATION_MAPPING[pair]
-
- def compare(self, op: str, other: Var) -> Var:
- """Compare two vars with inequalities.
-
- Args:
- op: The comparison operator.
- other: The other var to compare with.
-
- Returns:
- The comparison result.
- """
- return self.operation(op, other, bool)
-
- def __invert__(self) -> Var:
- """Invert a var.
-
- Returns:
- The inverted var.
- """
- return self.operation("!", type_=bool)
-
- def __neg__(self) -> Var:
- """Negate a var.
-
- Returns:
- The negated var.
- """
- return self.operation(fn="-")
-
- def __abs__(self) -> Var:
- """Get the absolute value of a var.
-
- Returns:
- A var with the absolute value.
- """
- return self.operation(fn="Math.abs")
-
- def length(self) -> Var:
- """Get the length of a list var.
-
- Returns:
- A var with the absolute value.
-
- Raises:
- VarTypeError: If the var is not a list.
- """
- if not types._issubclass(self._var_type, List):
- raise VarTypeError(f"Cannot get length of non-list var {self}.")
- return self._replace(
- _var_name=f"{self._var_name}.length",
- _var_type=int,
- _var_is_string=False,
- )
-
- def _type(self) -> Var:
- """Get the type of the Var in Javascript.
-
- Returns:
- A var representing the type check.
- """
- return self._replace(
- _var_name=f"typeof {self._var_full_name}",
- _var_type=str,
- _var_is_string=False,
- _var_full_name_needs_state_prefix=False,
- )
-
- def __eq__(self, other: Union[Var, Type]) -> Var:
- """Perform an equality comparison.
-
- Args:
- other: The other var to compare with.
-
- Returns:
- A var representing the equality comparison.
- """
- for python_types, js_type in PYTHON_JS_TYPE_MAP.items():
- if not isinstance(other, Var) and other in python_types:
- return self.compare("===", Var.create(js_type, _var_is_string=True)) # type: ignore
- return self.compare("===", other)
-
- def __ne__(self, other: Union[Var, Type]) -> Var:
- """Perform an inequality comparison.
-
- Args:
- other: The other var to compare with.
-
- Returns:
- A var representing the inequality comparison.
- """
- for python_types, js_type in PYTHON_JS_TYPE_MAP.items():
- if not isinstance(other, Var) and other in python_types:
- return self.compare("!==", Var.create(js_type, _var_is_string=True)) # type: ignore
- return self.compare("!==", other)
-
- def __gt__(self, other: Var) -> Var:
- """Perform a greater than comparison.
-
- Args:
- other: The other var to compare with.
-
- Returns:
- A var representing the greater than comparison.
- """
- return self.compare(">", other)
-
- def __ge__(self, other: Var) -> Var:
- """Perform a greater than or equal to comparison.
-
- Args:
- other: The other var to compare with.
-
- Returns:
- A var representing the greater than or equal to comparison.
- """
- return self.compare(">=", other)
-
- def __lt__(self, other: Var) -> Var:
- """Perform a less than comparison.
-
- Args:
- other: The other var to compare with.
-
- Returns:
- A var representing the less than comparison.
- """
- return self.compare("<", other)
-
- def __le__(self, other: Var) -> Var:
- """Perform a less than or equal to comparison.
-
- Args:
- other: The other var to compare with.
-
- Returns:
- A var representing the less than or equal to comparison.
- """
- return self.compare("<=", other)
-
- def __add__(self, other: Var, flip=False) -> Var:
- """Add two vars.
-
- Args:
- other: The other var to add.
- flip: Whether to flip operands.
-
- Returns:
- A var representing the sum.
- """
- other_type = other._var_type if isinstance(other, Var) else type(other)
- # For list-list addition, javascript concatenates the content of the lists instead of
- # merging the list, and for that reason we use the spread operator available through spreadArraysOrObjects
- # utility function
- if (
- types.get_base_class(self._var_type) == list
- and types.get_base_class(other_type) == list
- ):
- return self.operation(
- ",", other, fn="spreadArraysOrObjects", flip=flip
- )._replace(
- merge_var_data=VarData(
- imports={
- f"/{constants.Dirs.STATE_PATH}": [
- ImportVar(tag="spreadArraysOrObjects")
- ]
- },
- ),
- )
- return self.operation("+", other, flip=flip)
-
- def __radd__(self, other: Var) -> Var:
- """Add two vars.
-
- Args:
- other: The other var to add.
-
- Returns:
- A var representing the sum.
- """
- return self.__add__(other=other, flip=True)
-
- def __sub__(self, other: Var) -> Var:
- """Subtract two vars.
-
- Args:
- other: The other var to subtract.
-
- Returns:
- A var representing the difference.
- """
- return self.operation("-", other)
-
- def __rsub__(self, other: Var) -> Var:
- """Subtract two vars.
-
- Args:
- other: The other var to subtract.
-
- Returns:
- A var representing the difference.
- """
- return self.operation("-", other, flip=True)
-
- def __mul__(self, other: Var, flip=True) -> Var:
- """Multiply two vars.
-
- Args:
- other: The other var to multiply.
- flip: Whether to flip operands
-
- Returns:
- A var representing the product.
- """
- other_type = other._var_type if isinstance(other, Var) else type(other)
- # For str-int multiplication, we use the repeat function.
- # i.e "hello" * 2 is equivalent to "hello".repeat(2) in js.
- if (types.get_base_class(self._var_type), types.get_base_class(other_type)) in [
- (int, str),
- (str, int),
- ]:
- return self.operation(other=other, fn="repeat", invoke_fn=True)
-
- # For list-int multiplication, we use the Array function.
- # i.e ["hello"] * 2 is equivalent to Array(2).fill().map(() => ["hello"]).flat() in js.
- if (types.get_base_class(self._var_type), types.get_base_class(other_type)) in [
- (int, list),
- (list, int),
- ]:
- other_name = other._var_full_name if isinstance(other, Var) else other
- name = f"Array({other_name}).fill().map(() => {self._var_full_name}).flat()"
- return self._replace(
- _var_name=name,
- _var_type=str,
- _var_is_string=False,
- _var_full_name_needs_state_prefix=False,
- )
-
- return self.operation("*", other)
-
- def __rmul__(self, other: Var) -> Var:
- """Multiply two vars.
-
- Args:
- other: The other var to multiply.
-
- Returns:
- A var representing the product.
- """
- return self.__mul__(other=other, flip=True)
-
- def __pow__(self, other: Var) -> Var:
- """Raise a var to a power.
-
- Args:
- other: The power to raise to.
-
- Returns:
- A var representing the power.
- """
- return self.operation(",", other, fn="Math.pow")
-
- def __rpow__(self, other: Var) -> Var:
- """Raise a var to a power.
-
- Args:
- other: The power to raise to.
-
- Returns:
- A var representing the power.
- """
- return self.operation(",", other, flip=True, fn="Math.pow")
-
- def __truediv__(self, other: Var) -> Var:
- """Divide two vars.
-
- Args:
- other: The other var to divide.
-
- Returns:
- A var representing the quotient.
- """
- return self.operation("/", other)
-
- def __rtruediv__(self, other: Var) -> Var:
- """Divide two vars.
-
- Args:
- other: The other var to divide.
-
- Returns:
- A var representing the quotient.
- """
- return self.operation("/", other, flip=True)
-
- def __floordiv__(self, other: Var) -> Var:
- """Divide two vars.
-
- Args:
- other: The other var to divide.
-
- Returns:
- A var representing the quotient.
- """
- return self.operation("/", other, fn="Math.floor")
-
- def __mod__(self, other: Var) -> Var:
- """Get the remainder of two vars.
-
- Args:
- other: The other var to divide.
-
- Returns:
- A var representing the remainder.
- """
- return self.operation("%", other)
-
- def __rmod__(self, other: Var) -> Var:
- """Get the remainder of two vars.
-
- Args:
- other: The other var to divide.
-
- Returns:
- A var representing the remainder.
- """
- return self.operation("%", other, flip=True)
-
- def __and__(self, other: Var) -> Var:
- """Perform a logical and.
-
- Args:
- other: The other var to perform the logical AND with.
-
- Returns:
- A var representing the logical AND.
-
- Note:
- This method provides behavior specific to JavaScript, where it returns the JavaScript
- equivalent code (using the '&&' operator) of a logical AND operation.
- In JavaScript, the
- logical OR operator '&&' is used for Boolean logic, and this method emulates that behavior
- by returning the equivalent code as a Var instance.
-
- In Python, logical AND 'and' operates differently, evaluating expressions immediately, making
- it challenging to override the behavior entirely.
- Therefore, this method leverages the
- bitwise AND '__and__' operator for custom JavaScript-like behavior.
-
- Example:
- >>> var1 = Var.create(True)
- >>> var2 = Var.create(False)
- >>> js_code = var1 & var2
- >>> print(js_code._var_full_name)
- '(true && false)'
- """
- return self.operation("&&", other, type_=bool)
-
- def __rand__(self, other: Var) -> Var:
- """Perform a logical and.
-
- Args:
- other: The other var to perform the logical AND with.
-
- Returns:
- A var representing the logical AND.
-
- Note:
- This method provides behavior specific to JavaScript, where it returns the JavaScript
- equivalent code (using the '&&' operator) of a logical AND operation.
- In JavaScript, the
- logical OR operator '&&' is used for Boolean logic, and this method emulates that behavior
- by returning the equivalent code as a Var instance.
-
- In Python, logical AND 'and' operates differently, evaluating expressions immediately, making
- it challenging to override the behavior entirely.
- Therefore, this method leverages the
- bitwise AND '__rand__' operator for custom JavaScript-like behavior.
-
- Example:
- >>> var1 = Var.create(True)
- >>> var2 = Var.create(False)
- >>> js_code = var1 & var2
- >>> print(js_code._var_full_name)
- '(false && true)'
- """
- return self.operation("&&", other, type_=bool, flip=True)
-
- def __or__(self, other: Var) -> Var:
- """Perform a logical or.
-
- Args:
- other: The other var to perform the logical or with.
-
- Returns:
- A var representing the logical or.
-
- Note:
- This method provides behavior specific to JavaScript, where it returns the JavaScript
- equivalent code (using the '||' operator) of a logical OR operation. In JavaScript, the
- logical OR operator '||' is used for Boolean logic, and this method emulates that behavior
- by returning the equivalent code as a Var instance.
-
- In Python, logical OR 'or' operates differently, evaluating expressions immediately, making
- it challenging to override the behavior entirely. Therefore, this method leverages the
- bitwise OR '__or__' operator for custom JavaScript-like behavior.
-
- Example:
- >>> var1 = Var.create(True)
- >>> var2 = Var.create(False)
- >>> js_code = var1 | var2
- >>> print(js_code._var_full_name)
- '(true || false)'
- """
- return self.operation("||", other, type_=bool)
-
- def __ror__(self, other: Var) -> Var:
- """Perform a logical or.
-
- Args:
- other: The other var to perform the logical or with.
-
- Returns:
- A var representing the logical or.
-
- Note:
- This method provides behavior specific to JavaScript, where it returns the JavaScript
- equivalent code (using the '||' operator) of a logical OR operation. In JavaScript, the
- logical OR operator '||' is used for Boolean logic, and this method emulates that behavior
- by returning the equivalent code as a Var instance.
-
- In Python, logical OR 'or' operates differently, evaluating expressions immediately, making
- it challenging to override the behavior entirely. Therefore, this method leverages the
- bitwise OR '__or__' operator for custom JavaScript-like behavior.
-
- Example:
- >>> var1 = Var.create(True)
- >>> var2 = Var.create(False)
- >>> js_code = var1 | var2
- >>> print(js_code)
- 'false || true'
- """
- return self.operation("||", other, type_=bool, flip=True)
-
- def __contains__(self, _: Any) -> Var:
- """Override the 'in' operator to alert the user that it is not supported.
-
- Raises:
- VarTypeError: the operation is not supported
- """
- raise VarTypeError(
- "'in' operator not supported for Var types, use Var.contains() instead."
- )
-
- def contains(self, other: Any) -> Var:
- """Check if a var contains the object `other`.
-
- Args:
- other: The object to check.
-
- Raises:
- VarTypeError: If the var is not a valid type: dict, list, tuple or str.
-
- Returns:
- A var representing the contain check.
- """
- if not (types._issubclass(self._var_type, Union[dict, list, tuple, str, set])):
- raise VarTypeError(
- f"Var {self._var_full_name} of type {self._var_type} does not support contains check."
- )
- method = (
- "hasOwnProperty"
- if types.get_base_class(self._var_type) == dict
- else "includes"
- )
- if isinstance(other, str):
- other = Var.create(json.dumps(other), _var_is_string=True)
- elif not isinstance(other, Var):
- other = Var.create(other)
- if types._issubclass(self._var_type, Dict):
- return self._replace(
- _var_name=f"{self._var_name}.{method}({other._var_full_name})",
- _var_type=bool,
- _var_is_string=False,
- merge_var_data=other._var_data,
- )
- else: # str, list, tuple
- # For strings, the left operand must be a string.
- if types._issubclass(self._var_type, str) and not types._issubclass(
- other._var_type, str
- ):
- raise VarTypeError(
- f"'in ' requires string as left operand, not {other._var_type}"
- )
- return self._replace(
- _var_name=f"{self._var_name}.includes({other._var_full_name})",
- _var_type=bool,
- _var_is_string=False,
- merge_var_data=other._var_data,
- )
-
- def reverse(self) -> Var:
- """Reverse a list var.
-
- Raises:
- VarTypeError: If the var is not a list.
-
- Returns:
- A var with the reversed list.
- """
- if not types._issubclass(self._var_type, list):
- raise VarTypeError(f"Cannot reverse non-list var {self._var_full_name}.")
-
- return self._replace(
- _var_name=f"[...{self._var_full_name}].reverse()",
- _var_is_string=False,
- _var_full_name_needs_state_prefix=False,
- )
-
- def lower(self) -> Var:
- """Convert a string var to lowercase.
-
- Returns:
- A var with the lowercase string.
-
- Raises:
- VarTypeError: If the var is not a string.
- """
- if not types._issubclass(self._var_type, str):
- raise VarTypeError(
- f"Cannot convert non-string var {self._var_full_name} to lowercase."
- )
-
- return self._replace(
- _var_name=f"{self._var_name}.toLowerCase()",
- _var_is_string=False,
- _var_type=str,
- )
-
- def upper(self) -> Var:
- """Convert a string var to uppercase.
-
- Returns:
- A var with the uppercase string.
-
- Raises:
- VarTypeError: If the var is not a string.
- """
- if not types._issubclass(self._var_type, str):
- raise VarTypeError(
- f"Cannot convert non-string var {self._var_full_name} to uppercase."
- )
-
- return self._replace(
- _var_name=f"{self._var_name}.toUpperCase()",
- _var_is_string=False,
- _var_type=str,
- )
-
- def strip(self, other: str | Var[str] = " ") -> Var:
- """Strip a string var.
-
- Args:
- other: The string to strip the var with.
-
- Returns:
- A var with the stripped string.
-
- Raises:
- VarTypeError: If the var is not a string.
- """
- if not types._issubclass(self._var_type, str):
- raise VarTypeError(f"Cannot strip non-string var {self._var_full_name}.")
-
- other = Var.create_safe(json.dumps(other)) if isinstance(other, str) else other
-
- return self._replace(
- _var_name=f"{self._var_name}.replace(/^${other._var_full_name}|${other._var_full_name}$/g, '')",
- _var_is_string=False,
- merge_var_data=other._var_data,
- )
-
- def split(self, other: str | Var[str] = " ") -> Var:
- """Split a string var into a list.
-
- Args:
- other: The string to split the var with.
-
- Returns:
- A var with the list.
-
- Raises:
- VarTypeError: If the var is not a string.
- """
- if not types._issubclass(self._var_type, str):
- raise VarTypeError(f"Cannot split non-string var {self._var_full_name}.")
-
- other = Var.create_safe(json.dumps(other)) if isinstance(other, str) else other
-
- return self._replace(
- _var_name=f"{self._var_name}.split({other._var_full_name})",
- _var_is_string=False,
- _var_type=List[str],
- merge_var_data=other._var_data,
- )
-
- def join(self, other: str | Var[str] | None = None) -> Var:
- """Join a list var into a string.
-
- Args:
- other: The string to join the list with.
-
- Returns:
- A var with the string.
-
- Raises:
- VarTypeError: If the var is not a list.
- """
- if not types._issubclass(self._var_type, list):
- raise VarTypeError(f"Cannot join non-list var {self._var_full_name}.")
-
- if other is None:
- other = Var.create_safe('""')
- if isinstance(other, str):
- other = Var.create_safe(json.dumps(other))
- else:
- other = Var.create_safe(other)
-
- return self._replace(
- _var_name=f"{self._var_name}.join({other._var_full_name})",
- _var_is_string=False,
- _var_type=str,
- merge_var_data=other._var_data,
- )
-
- def foreach(self, fn: Callable) -> Var:
- """Return a list of components. after doing a foreach on this var.
-
- Args:
- fn: The function to call on each component.
-
- Returns:
- A var representing foreach operation.
-
- Raises:
- VarTypeError: If the var is not a list.
- """
- inner_types = get_args(self._var_type)
- if not inner_types:
- raise VarTypeError(
- f"Cannot foreach over non-sequence var {self._var_full_name} of type {self._var_type}."
- )
- arg = BaseVar(
- _var_name=get_unique_variable_name(),
- _var_type=inner_types[0],
- )
- index = BaseVar(
- _var_name=get_unique_variable_name(),
- _var_type=int,
- )
- fn_signature = inspect.signature(fn)
- fn_args = (arg, index)
- fn_ret = fn(*fn_args[: len(fn_signature.parameters)])
- return self._replace(
- _var_name=f"{self._var_full_name}.map(({arg._var_name}, {index._var_name}) => {fn_ret})",
- _var_is_string=False,
- )
-
- @classmethod
- def range(
- cls,
- v1: Var | int = 0,
- v2: Var | int | None = None,
- step: Var | int | None = None,
- ) -> Var:
- """Return an iterator over indices from v1 to v2 (or 0 to v1).
-
- Args:
- v1: The start of the range or end of range if v2 is not given.
- v2: The end of the range.
- step: The number of numbers between each item.
-
- Returns:
- A var representing range operation.
-
- Raises:
- VarTypeError: If the var is not an int.
- """
- if not isinstance(v1, Var):
- v1 = Var.create_safe(v1)
- if v1._var_type != int:
- raise VarTypeError(f"Cannot get range on non-int var {v1._var_full_name}.")
- if not isinstance(v2, Var):
- v2 = Var.create(v2)
- if v2 is None:
- v2 = Var.create_safe("undefined")
- elif v2._var_type != int:
- raise VarTypeError(f"Cannot get range on non-int var {v2._var_full_name}.")
-
- if not isinstance(step, Var):
- step = Var.create(step)
- if step is None:
- step = Var.create_safe(1)
- elif step._var_type != int:
- raise VarTypeError(
- f"Cannot get range on non-int var {step._var_full_name}."
- )
-
- return BaseVar(
- _var_name=f"Array.from(range({v1._var_full_name}, {v2._var_full_name}, {step._var_name}))",
- _var_type=List[int],
- _var_is_local=False,
- _var_data=VarData.merge(
- v1._var_data,
- v2._var_data,
- step._var_data,
- VarData(
- imports={
- "/utils/helpers/range.js": [
- ImportVar(tag="range", is_default=True),
- ],
- },
- ),
- ),
- )
-
- def to(self, type_: Type) -> Var:
- """Convert the type of the var.
-
- Args:
- type_: The type to convert to.
-
- Returns:
- The converted var.
- """
- return self._replace(_var_type=type_)
-
- def as_ref(self) -> Var:
- """Convert the var to a ref.
-
- Returns:
- The var as a ref.
- """
- return self._replace(
- _var_name=f"refs['{self._var_full_name}']",
- _var_is_local=True,
- _var_is_string=False,
- _var_full_name_needs_state_prefix=False,
- merge_var_data=VarData(
- imports={
- f"/{constants.Dirs.STATE_PATH}": [imports.ImportVar(tag="refs")],
- },
- ),
- )
-
- @property
- def _var_full_name(self) -> str:
- """Get the full name of the var.
-
- Returns:
- The full name of the var.
- """
- if not self._var_full_name_needs_state_prefix:
- return self._var_name
- return (
- self._var_name
- if self._var_data is None or self._var_data.state == ""
- else ".".join(
- [format.format_state_name(self._var_data.state), self._var_name]
- )
- )
-
- def _var_set_state(self, state: Type[BaseState] | str) -> Any:
- """Set the state of the var.
-
- Args:
- state: The state to set or the full name of the state.
-
- Returns:
- The var with the set state.
- """
- state_name = state if isinstance(state, str) else state.get_full_name()
- new_var_data = VarData(
- state=state_name,
- hooks={
- "const {0} = useContext(StateContexts.{0})".format(
- format.format_state_name(state_name)
- ): None
- },
- imports={
- f"/{constants.Dirs.CONTEXTS_PATH}": [ImportVar(tag="StateContexts")],
- "react": [ImportVar(tag="useContext")],
- },
- )
- self._var_data = VarData.merge(self._var_data, new_var_data)
- self._var_full_name_needs_state_prefix = True
- return self
-
- @property
- def _var_state(self) -> str:
- """Compat method for getting the state.
-
- Returns:
- The state name associated with the var.
- """
- return self._var_data.state if self._var_data else ""
-
- @property
- def _var_name_unwrapped(self) -> str:
- """Get the var str without wrapping in curly braces.
-
- Returns:
- The str var without the wrapped curly braces
- """
- from reflex.style import Style
-
- type_ = (
- get_origin(self._var_type)
- if types.is_generic_alias(self._var_type)
- else self._var_type
- )
- wrapped_var = str(self)
-
- return (
- wrapped_var
- if not self._var_state
- and types._issubclass(type_, dict)
- or types._issubclass(type_, Style)
- else wrapped_var.strip("{}")
- )
-
-
-# Allow automatic serialization of Var within JSON structures
-serializers.serializer(_encode_var)
-
-
-@dataclasses.dataclass(
- eq=False,
- **{"slots": True} if sys.version_info >= (3, 10) else {},
-)
-class BaseVar(Var):
- """A base (non-computed) var of the app state."""
-
- # The name of the var.
- _var_name: str = dataclasses.field()
-
- # The type of the var.
- _var_type: Type = dataclasses.field(default=Any)
-
- # Whether this is a local javascript variable.
- _var_is_local: bool = dataclasses.field(default=False)
-
- # Whether the var is a string literal.
- _var_is_string: bool = dataclasses.field(default=False)
-
- # _var_full_name should be prefixed with _var_state
- _var_full_name_needs_state_prefix: bool = dataclasses.field(default=False)
-
- # Extra metadata associated with the Var
- _var_data: Optional[VarData] = dataclasses.field(default=None)
-
- def __hash__(self) -> int:
- """Define a hash function for a var.
-
- Returns:
- The hash of the var.
- """
- return hash((self._var_name, str(self._var_type)))
-
- def get_default_value(self) -> Any:
- """Get the default value of the var.
-
- Returns:
- The default value of the var.
-
- Raises:
- ImportError: If the var is a dataframe and pandas is not installed.
- """
- if types.is_optional(self._var_type):
- return None
-
- type_ = (
- get_origin(self._var_type)
- if types.is_generic_alias(self._var_type)
- else self._var_type
- )
- if type_ is Literal:
- args = get_args(self._var_type)
- return args[0] if args else None
- if issubclass(type_, str):
- return ""
- if issubclass(type_, types.get_args(Union[int, float])):
- return 0
- if issubclass(type_, bool):
- return False
- if issubclass(type_, list):
- return []
- if issubclass(type_, dict):
- return {}
- if issubclass(type_, tuple):
- return ()
- if types.is_dataframe(type_):
- try:
- import pandas as pd
-
- return pd.DataFrame()
- except ImportError as e:
- raise ImportError(
- "Please install pandas to use dataframes in your app."
- ) from e
- return set() if issubclass(type_, set) else None
-
- def get_setter_name(self, include_state: bool = True) -> str:
- """Get the name of the var's generated setter function.
-
- Args:
- include_state: Whether to include the state name in the setter name.
-
- Returns:
- The name of the setter function.
- """
- setter = constants.SETTER_PREFIX + self._var_name
- if self._var_data is None:
- return setter
- if not include_state or self._var_data.state == "":
- return setter
- return ".".join((self._var_data.state, setter))
-
- def get_setter(self) -> Callable[[BaseState, Any], None]:
- """Get the var's setter function.
-
- Returns:
- A function that that creates a setter for the var.
- """
-
- def setter(state: BaseState, value: Any):
- """Get the setter for the var.
-
- Args:
- state: The state within which we add the setter function.
- value: The value to set.
- """
- if self._var_type in [int, float]:
- try:
- value = self._var_type(value)
- setattr(state, self._var_name, value)
- except ValueError:
- console.debug(
- f"{type(state).__name__}.{self._var_name}: Failed conversion of {value} to '{self._var_type.__name__}'. Value not set.",
- )
- else:
- setattr(state, self._var_name, value)
-
- setter.__qualname__ = self.get_setter_name()
-
- return setter
-
-
-@dataclasses.dataclass(init=False, eq=False)
-class ComputedVar(Var, property):
- """A field with computed getters."""
-
- # Whether to track dependencies and cache computed values
- _cache: bool = dataclasses.field(default=False)
-
- _initial_value: Any | types.Unset = dataclasses.field(default_factory=types.Unset)
-
- def __init__(
- self,
- fget: Callable[[BaseState], Any],
- initial_value: Any | types.Unset = types.Unset(),
- cache: bool = False,
- **kwargs,
- ):
- """Initialize a ComputedVar.
-
- Args:
- fget: The getter function.
- initial_value: The initial value of the computed var.
- cache: Whether to cache the computed value.
- **kwargs: additional attributes to set on the instance
- """
- self._initial_value = initial_value
- self._cache = cache
- property.__init__(self, fget)
- kwargs["_var_name"] = kwargs.pop("_var_name", fget.__name__)
- kwargs["_var_type"] = kwargs.pop("_var_type", self._determine_var_type())
- BaseVar.__init__(self, **kwargs) # type: ignore
-
- @property
- def _cache_attr(self) -> str:
- """Get the attribute used to cache the value on the instance.
-
- Returns:
- An attribute name.
- """
- return f"__cached_{self._var_name}"
-
- def __get__(self, instance, owner):
- """Get the ComputedVar value.
-
- If the value is already cached on the instance, return the cached value.
-
- Args:
- instance: the instance of the class accessing this computed var.
- owner: the class that this descriptor is attached to.
-
- Returns:
- The value of the var for the given instance.
- """
- if instance is None or not self._cache:
- return super().__get__(instance, owner)
-
- # handle caching
- if not hasattr(instance, self._cache_attr):
- setattr(instance, self._cache_attr, super().__get__(instance, owner))
- # Ensure the computed var gets serialized to redis.
- instance._was_touched = True
- return getattr(instance, self._cache_attr)
-
- def _deps(
- self,
- objclass: Type,
- obj: FunctionType | CodeType | None = None,
- self_name: Optional[str] = None,
- ) -> set[str]:
- """Determine var dependencies of this ComputedVar.
-
- Save references to attributes accessed on "self". Recursively called
- when the function makes a method call on "self" or define comprehensions
- or nested functions that may reference "self".
-
- Args:
- objclass: the class obj this ComputedVar is attached to.
- obj: the object to disassemble (defaults to the fget function).
- self_name: if specified, look for this name in LOAD_FAST and LOAD_DEREF instructions.
-
- Returns:
- A set of variable names accessed by the given obj.
-
- Raises:
- VarValueError: if the function references the get_state, parent_state, or substates attributes
- (cannot track deps in a related state, only implicitly via parent state).
- """
- d = set()
- if obj is None:
- fget = property.__getattribute__(self, "fget")
- if fget is not None:
- obj = cast(FunctionType, fget)
- else:
- return set()
- with contextlib.suppress(AttributeError):
- # unbox functools.partial
- obj = cast(FunctionType, obj.func) # type: ignore
- with contextlib.suppress(AttributeError):
- # unbox EventHandler
- obj = cast(FunctionType, obj.fn) # type: ignore
-
- if self_name is None and isinstance(obj, FunctionType):
- try:
- # the first argument to the function is the name of "self" arg
- self_name = obj.__code__.co_varnames[0]
- except (AttributeError, IndexError):
- self_name = None
- if self_name is None:
- # cannot reference attributes on self if method takes no args
- return set()
-
- invalid_names = ["get_state", "parent_state", "substates", "get_substate"]
- self_is_top_of_stack = False
- for instruction in dis.get_instructions(obj):
- if (
- instruction.opname in ("LOAD_FAST", "LOAD_DEREF")
- and instruction.argval == self_name
- ):
- # bytecode loaded the class instance to the top of stack, next load instruction
- # is referencing an attribute on self
- self_is_top_of_stack = True
- continue
- if self_is_top_of_stack and instruction.opname in (
- "LOAD_ATTR",
- "LOAD_METHOD",
- ):
- try:
- ref_obj = getattr(objclass, instruction.argval)
- except Exception:
- ref_obj = None
- if instruction.argval in invalid_names:
- raise VarValueError(
- f"Cached var {self._var_full_name} cannot access arbitrary state via `{instruction.argval}`."
- )
- if callable(ref_obj):
- # recurse into callable attributes
- d.update(
- self._deps(
- objclass=objclass,
- obj=ref_obj,
- )
- )
- else:
- # normal attribute access
- d.add(instruction.argval)
- elif instruction.opname == "LOAD_CONST" and isinstance(
- instruction.argval, CodeType
- ):
- # recurse into nested functions / comprehensions, which can reference
- # instance attributes from the outer scope
- d.update(
- self._deps(
- objclass=objclass,
- obj=instruction.argval,
- self_name=self_name,
- )
- )
- self_is_top_of_stack = False
- return d
-
- def mark_dirty(self, instance) -> None:
- """Mark this ComputedVar as dirty.
-
- Args:
- instance: the state instance that needs to recompute the value.
- """
- with contextlib.suppress(AttributeError):
- delattr(instance, self._cache_attr)
-
- def _determine_var_type(self) -> Type:
- """Get the type of the var.
-
- Returns:
- The type of the var.
- """
- hints = get_type_hints(property.__getattribute__(self, "fget"))
- if "return" in hints:
- return hints["return"]
- return Any
-
-
-def computed_var(
- fget: Callable[[BaseState], Any] | None = None,
- initial_value: Any | None = None,
- cache: bool = False,
- **kwargs,
-) -> ComputedVar | Callable[[Callable[[BaseState], Any]], ComputedVar]:
- """A ComputedVar decorator with or without kwargs.
-
- Args:
- fget: The getter function.
- initial_value: The initial value of the computed var.
- cache: Whether to cache the computed value.
- **kwargs: additional attributes to set on the instance
-
- Returns:
- A ComputedVar instance.
- """
- if fget is not None:
- return ComputedVar(fget=fget, cache=cache)
-
- def wrapper(fget):
- return ComputedVar(
- fget=fget,
- initial_value=initial_value,
- cache=cache,
- **kwargs,
- )
-
- return wrapper
-
-
-# Partial function of computed_var with cache=True
-cached_var = functools.partial(computed_var, cache=True)
-
-
-class CallableVar(BaseVar):
- """Decorate a Var-returning function to act as both a Var and a function.
-
- This is used as a compatibility shim for replacing Var objects in the
- API with functions that return a family of Var.
- """
-
- def __init__(self, fn: Callable[..., BaseVar]):
- """Initialize a CallableVar.
-
- Args:
- fn: The function to decorate (must return Var)
- """
- self.fn = fn
- default_var = fn()
- super().__init__(**dataclasses.asdict(default_var))
-
- def __call__(self, *args, **kwargs) -> BaseVar:
- """Call the decorated function.
-
- Args:
- *args: The args to pass to the function.
- **kwargs: The kwargs to pass to the function.
-
- Returns:
- The Var returned from calling the function.
- """
- return self.fn(*args, **kwargs)
-
-
-def get_uuid_string_var() -> Var:
- """Return a var that generates UUIDs via .web/utils/state.js.
-
- Returns:
- the var to generate UUIDs at runtime.
- """
- from reflex.utils.imports import ImportVar
-
- unique_uuid_var_data = VarData(
- imports={f"/{constants.Dirs.STATE_PATH}": {ImportVar(tag="generateUUID")}} # type: ignore
- )
-
- return BaseVar(
- _var_name="generateUUID()", _var_type=str, _var_data=unique_uuid_var_data
- )
diff --git a/reflex/vars.pyi b/reflex/vars.pyi
deleted file mode 100644
index fb2ed4657..000000000
--- a/reflex/vars.pyi
+++ /dev/null
@@ -1,167 +0,0 @@
-""" Generated with stubgen from mypy, then manually edited, do not regen."""
-
-from __future__ import annotations
-
-from dataclasses import dataclass
-from _typeshed import Incomplete
-from reflex import constants as constants
-from reflex.base import Base as Base
-from reflex.state import State as State
-from reflex.state import BaseState as BaseState
-from reflex.utils import console as console, format as format, types as types
-from reflex.utils.imports import ImportVar
-from types import FunctionType
-from typing import (
- Any,
- Callable,
- Dict,
- Iterable,
- List,
- Optional,
- Set,
- Tuple,
- Type,
- Union,
- overload,
- _GenericAlias, # type: ignore
-)
-
-USED_VARIABLES: Incomplete
-
-def get_unique_variable_name() -> str: ...
-def _encode_var(value: Var) -> str: ...
-def _decode_var(value: str) -> tuple[VarData, str]: ...
-def _extract_var_data(value: Iterable) -> list[VarData | None]: ...
-
-class VarData(Base):
- state: str
- imports: dict[str, set[ImportVar]]
- hooks: Dict[str, None]
- interpolations: List[Tuple[int, int]]
- @classmethod
- def merge(cls, *others: VarData | None) -> VarData | None: ...
-
-class Var:
- _var_name: str
- _var_type: Type
- _var_is_local: bool = False
- _var_is_string: bool = False
- _var_full_name_needs_state_prefix: bool = False
- _var_data: VarData | None = None
- @classmethod
- def create(
- cls, value: Any, _var_is_local: bool = False, _var_is_string: bool = False
- ) -> Optional[Var]: ...
- @classmethod
- def create_safe(
- cls, value: Any, _var_is_local: bool = False, _var_is_string: bool = False
- ) -> Var: ...
- @classmethod
- def __class_getitem__(cls, type_: Type) -> _GenericAlias: ...
- def _replace(self, merge_var_data=None, **kwargs: Any) -> Var: ...
- def equals(self, other: Var) -> bool: ...
- def to_string(self) -> Var: ...
- def __hash__(self) -> int: ...
- def __format__(self, format_spec: str) -> str: ...
- def __getitem__(self, i: Any) -> Var: ...
- def __getattribute__(self, name: str) -> Var: ...
- def operation(
- self,
- op: str = ...,
- other: Optional[Var] = ...,
- type_: Optional[Type] = ...,
- flip: bool = ...,
- fn: Optional[str] = ...,
- ) -> Var: ...
- def compare(self, op: str, other: Var) -> Var: ...
- def __invert__(self) -> Var: ...
- def __neg__(self) -> Var: ...
- def __abs__(self) -> Var: ...
- def length(self) -> Var: ...
- def __eq__(self, other: Var) -> Var: ...
- def __ne__(self, other: Var) -> Var: ...
- def __gt__(self, other: Var) -> Var: ...
- def __ge__(self, other: Var) -> Var: ...
- def __lt__(self, other: Var) -> Var: ...
- def __le__(self, other: Var) -> Var: ...
- def __add__(self, other: Var) -> Var: ...
- def __radd__(self, other: Var) -> Var: ...
- def __sub__(self, other: Var) -> Var: ...
- def __rsub__(self, other: Var) -> Var: ...
- def __mul__(self, other: Var) -> Var: ...
- def __rmul__(self, other: Var) -> Var: ...
- def __pow__(self, other: Var) -> Var: ...
- def __rpow__(self, other: Var) -> Var: ...
- def __truediv__(self, other: Var) -> Var: ...
- def __rtruediv__(self, other: Var) -> Var: ...
- def __floordiv__(self, other: Var) -> Var: ...
- def __mod__(self, other: Var) -> Var: ...
- def __rmod__(self, other: Var) -> Var: ...
- def __and__(self, other: Var) -> Var: ...
- def __rand__(self, other: Var) -> Var: ...
- def __or__(self, other: Var) -> Var: ...
- def __ror__(self, other: Var) -> Var: ...
- def __contains__(self, _: Any) -> Var: ...
- def contains(self, other: Any) -> Var: ...
- def reverse(self) -> Var: ...
- def foreach(self, fn: Callable) -> Var: ...
- @classmethod
- def range(
- cls,
- v1: Var | int = 0,
- v2: Var | int | None = None,
- step: Var | int | None = None,
- ) -> Var: ...
- def to(self, type_: Type) -> Var: ...
- def as_ref(self) -> Var: ...
- @property
- def _var_full_name(self) -> str: ...
- def _var_set_state(self, state: Type[BaseState] | str) -> Any: ...
-
-@dataclass(eq=False)
-class BaseVar(Var):
- _var_name: str
- _var_type: Any
- _var_is_local: bool = False
- _var_is_string: bool = False
- _var_full_name_needs_state_prefix: bool = False
- _var_data: VarData | None = None
- def __hash__(self) -> int: ...
- def get_default_value(self) -> Any: ...
- def get_setter_name(self, include_state: bool = ...) -> str: ...
- def get_setter(self) -> Callable[[BaseState, Any], None]: ...
-
-@dataclass(init=False)
-class ComputedVar(Var):
- _var_cache: bool
- fget: FunctionType
- @property
- def _cache_attr(self) -> str: ...
- def __get__(self, instance, owner): ...
- def _deps(self, objclass: Type, obj: Optional[FunctionType] = ...) -> Set[str]: ...
- def mark_dirty(self, instance) -> None: ...
- def _determine_var_type(self) -> Type: ...
- @overload
- def __init__(
- self,
- fget: Callable[[BaseState], Any],
- **kwargs,
- ) -> None: ...
- @overload
- def __init__(self, func) -> None: ...
-
-@overload
-def computed_var(
- fget: Callable[[BaseState], Any] | None = None,
- initial_value: Any | None = None,
- **kwargs,
-) -> Callable[[Callable[[Any], Any]], ComputedVar]: ...
-@overload
-def computed_var(fget: Callable[[Any], Any]) -> ComputedVar: ...
-def cached_var(fget: Callable[[Any], Any]) -> ComputedVar: ...
-
-class CallableVar(BaseVar):
- def __init__(self, fn: Callable[..., BaseVar]): ...
- def __call__(self, *args, **kwargs) -> BaseVar: ...
-
-def get_uuid_string_var() -> Var: ...
diff --git a/reflex/vars/__init__.py b/reflex/vars/__init__.py
new file mode 100644
index 000000000..1a4cebe19
--- /dev/null
+++ b/reflex/vars/__init__.py
@@ -0,0 +1,25 @@
+"""Immutable-Based Var System."""
+
+from .base import Field as Field
+from .base import LiteralVar as LiteralVar
+from .base import Var as Var
+from .base import VarData as VarData
+from .base import field as field
+from .base import get_unique_variable_name as get_unique_variable_name
+from .base import get_uuid_string_var as get_uuid_string_var
+from .base import var_operation as var_operation
+from .base import var_operation_return as var_operation_return
+from .function import FunctionStringVar as FunctionStringVar
+from .function import FunctionVar as FunctionVar
+from .function import VarOperationCall as VarOperationCall
+from .number import BooleanVar as BooleanVar
+from .number import LiteralBooleanVar as LiteralBooleanVar
+from .number import LiteralNumberVar as LiteralNumberVar
+from .number import NumberVar as NumberVar
+from .object import LiteralObjectVar as LiteralObjectVar
+from .object import ObjectVar as ObjectVar
+from .sequence import ArrayVar as ArrayVar
+from .sequence import ConcatVarOperation as ConcatVarOperation
+from .sequence import LiteralArrayVar as LiteralArrayVar
+from .sequence import LiteralStringVar as LiteralStringVar
+from .sequence import StringVar as StringVar
diff --git a/reflex/vars/base.py b/reflex/vars/base.py
new file mode 100644
index 000000000..b06e7b7c9
--- /dev/null
+++ b/reflex/vars/base.py
@@ -0,0 +1,2951 @@
+"""Collection of base classes."""
+
+from __future__ import annotations
+
+import contextlib
+import dataclasses
+import datetime
+import dis
+import functools
+import inspect
+import json
+import random
+import re
+import string
+import sys
+import warnings
+from types import CodeType, FunctionType
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ ClassVar,
+ Dict,
+ FrozenSet,
+ Generic,
+ Iterable,
+ List,
+ Literal,
+ NoReturn,
+ Optional,
+ Set,
+ Tuple,
+ Type,
+ TypeVar,
+ Union,
+ cast,
+ get_args,
+ overload,
+)
+
+from typing_extensions import (
+ ParamSpec,
+ TypeGuard,
+ deprecated,
+ get_type_hints,
+ override,
+)
+
+from reflex import constants
+from reflex.base import Base
+from reflex.utils import console, imports, serializers, types
+from reflex.utils.exceptions import (
+ VarAttributeError,
+ VarDependencyError,
+ VarTypeError,
+ VarValueError,
+)
+from reflex.utils.format import format_state_name
+from reflex.utils.imports import (
+ ImmutableParsedImportDict,
+ ImportDict,
+ ImportVar,
+ ParsedImportDict,
+ parse_imports,
+)
+from reflex.utils.types import (
+ GenericType,
+ Self,
+ _isinstance,
+ get_origin,
+ has_args,
+ unionize,
+)
+
+if TYPE_CHECKING:
+ from reflex.state import BaseState
+
+ from .function import FunctionVar
+ from .number import (
+ BooleanVar,
+ NumberVar,
+ )
+ from .object import ObjectVar
+ from .sequence import ArrayVar, StringVar
+
+
+VAR_TYPE = TypeVar("VAR_TYPE", covariant=True)
+OTHER_VAR_TYPE = TypeVar("OTHER_VAR_TYPE")
+
+warnings.filterwarnings("ignore", message="fields may not start with an underscore")
+
+
+@dataclasses.dataclass(
+ eq=False,
+ frozen=True,
+)
+class VarSubclassEntry:
+ """Entry for a Var subclass."""
+
+ var_subclass: Type[Var]
+ to_var_subclass: Type[ToOperation]
+ python_types: Tuple[GenericType, ...]
+
+
+_var_subclasses: List[VarSubclassEntry] = []
+_var_literal_subclasses: List[Tuple[Type[LiteralVar], VarSubclassEntry]] = []
+
+
+@dataclasses.dataclass(
+ eq=True,
+ frozen=True,
+)
+class VarData:
+ """Metadata associated with a x."""
+
+ # The name of the enclosing state.
+ state: str = dataclasses.field(default="")
+
+ # The name of the field in the state.
+ field_name: str = dataclasses.field(default="")
+
+ # Imports needed to render this var
+ imports: ImmutableParsedImportDict = dataclasses.field(default_factory=tuple)
+
+ # Hooks that need to be present in the component to render this var
+ hooks: Tuple[str, ...] = dataclasses.field(default_factory=tuple)
+
+ def __init__(
+ self,
+ state: str = "",
+ field_name: str = "",
+ imports: ImportDict | ParsedImportDict | None = None,
+ hooks: dict[str, None] | None = None,
+ ):
+ """Initialize the var data.
+
+ Args:
+ state: The name of the enclosing state.
+ field_name: The name of the field in the state.
+ imports: Imports needed to render this var.
+ hooks: Hooks that need to be present in the component to render this var.
+ """
+ immutable_imports: ImmutableParsedImportDict = tuple(
+ sorted(
+ ((k, tuple(sorted(v))) for k, v in parse_imports(imports or {}).items())
+ )
+ )
+ object.__setattr__(self, "state", state)
+ object.__setattr__(self, "field_name", field_name)
+ object.__setattr__(self, "imports", immutable_imports)
+ object.__setattr__(self, "hooks", tuple(hooks or {}))
+
+ def old_school_imports(self) -> ImportDict:
+ """Return the imports as a mutable dict.
+
+ Returns:
+ The imports as a mutable dict.
+ """
+ return dict((k, list(v)) for k, v in self.imports)
+
+ def merge(*all: VarData | None) -> VarData | None:
+ """Merge multiple var data objects.
+
+ Args:
+ *all: The var data objects to merge.
+
+ Returns:
+ The merged var data object.
+
+ # noqa: DAR102 *all
+ """
+ all_var_datas = list(filter(None, all))
+
+ if not all_var_datas:
+ return None
+
+ if len(all_var_datas) == 1:
+ return all_var_datas[0]
+
+ # Get the first non-empty field name or default to empty string.
+ field_name = next(
+ (var_data.field_name for var_data in all_var_datas if var_data.field_name),
+ "",
+ )
+
+ # Get the first non-empty state or default to empty string.
+ state = next(
+ (var_data.state for var_data in all_var_datas if var_data.state), ""
+ )
+
+ hooks = {hook: None for var_data in all_var_datas for hook in var_data.hooks}
+
+ _imports = imports.merge_imports(
+ *(var_data.imports for var_data in all_var_datas)
+ )
+
+ if state or _imports or hooks or field_name:
+ return VarData(
+ state=state,
+ field_name=field_name,
+ imports=_imports,
+ hooks=hooks,
+ )
+
+ return None
+
+ def __bool__(self) -> bool:
+ """Check if the var data is non-empty.
+
+ Returns:
+ True if any field is set to a non-default value.
+ """
+ return bool(self.state or self.imports or self.hooks or self.field_name)
+
+ @classmethod
+ def from_state(cls, state: Type[BaseState] | str, field_name: str = "") -> VarData:
+ """Set the state of the var.
+
+ Args:
+ state: The state to set or the full name of the state.
+ field_name: The name of the field in the state. Optional.
+
+ Returns:
+ The var with the set state.
+ """
+ from reflex.utils import format
+
+ state_name = state if isinstance(state, str) else state.get_full_name()
+ return VarData(
+ state=state_name,
+ field_name=field_name,
+ hooks={
+ "const {0} = useContext(StateContexts.{0})".format(
+ format.format_state_name(state_name)
+ ): None
+ },
+ imports={
+ f"$/{constants.Dirs.CONTEXTS_PATH}": [ImportVar(tag="StateContexts")],
+ "react": [ImportVar(tag="useContext")],
+ },
+ )
+
+
+def _decode_var_immutable(value: str) -> tuple[VarData | None, str]:
+ """Decode the state name from a formatted var.
+
+ Args:
+ value: The value to extract the state name from.
+
+ Returns:
+ The extracted state name and the value without the state name.
+ """
+ var_datas = []
+ if isinstance(value, str):
+ # fast path if there is no encoded VarData
+ if constants.REFLEX_VAR_OPENING_TAG not in value:
+ return None, value
+
+ offset = 0
+
+ # Find all tags.
+ while m := _decode_var_pattern.search(value):
+ start, end = m.span()
+ value = value[:start] + value[end:]
+
+ serialized_data = m.group(1)
+
+ if serialized_data.isnumeric() or (
+ serialized_data[0] == "-" and serialized_data[1:].isnumeric()
+ ):
+ # This is a global immutable var.
+ var = _global_vars[int(serialized_data)]
+ var_data = var._get_all_var_data()
+
+ if var_data is not None:
+ var_datas.append(var_data)
+ offset += end - start
+
+ return VarData.merge(*var_datas) if var_datas else None, value
+
+
+@dataclasses.dataclass(
+ eq=False,
+ frozen=True,
+)
+class Var(Generic[VAR_TYPE]):
+ """Base class for immutable vars."""
+
+ # The name of the var.
+ _js_expr: str = dataclasses.field()
+
+ # The type of the var.
+ _var_type: types.GenericType = dataclasses.field(default=Any)
+
+ # Extra metadata associated with the Var
+ _var_data: Optional[VarData] = dataclasses.field(default=None)
+
+ def __str__(self) -> str:
+ """String representation of the var. Guaranteed to be a valid Javascript expression.
+
+ Returns:
+ The name of the var.
+ """
+ return self._js_expr
+
+ @property
+ def _var_is_local(self) -> bool:
+ """Whether this is a local javascript variable.
+
+ Returns:
+ False
+ """
+ return False
+
+ @property
+ @deprecated("Use `_js_expr` instead.")
+ def _var_name(self) -> str:
+ """The name of the var.
+
+ Returns:
+ The name of the var.
+ """
+ return self._js_expr
+
+ @property
+ def _var_field_name(self) -> str:
+ """The name of the field.
+
+ Returns:
+ The name of the field.
+ """
+ var_data = self._get_all_var_data()
+ field_name = var_data.field_name if var_data else None
+ return field_name or self._js_expr
+
+ @property
+ @deprecated("Use `_js_expr` instead.")
+ def _var_name_unwrapped(self) -> str:
+ """The name of the var without extra curly braces.
+
+ Returns:
+ The name of the var.
+ """
+ return self._js_expr
+
+ @property
+ def _var_is_string(self) -> bool:
+ """Whether the var is a string literal.
+
+ Returns:
+ False
+ """
+ return False
+
+ def __init_subclass__(
+ cls, python_types: Tuple[GenericType, ...] | GenericType = types.Unset, **kwargs
+ ):
+ """Initialize the subclass.
+
+ Args:
+ python_types: The python types that the var represents.
+ **kwargs: Additional keyword arguments.
+ """
+ super().__init_subclass__(**kwargs)
+
+ if python_types is not types.Unset:
+ python_types = (
+ python_types if isinstance(python_types, tuple) else (python_types,)
+ )
+
+ @dataclasses.dataclass(
+ eq=False,
+ frozen=True,
+ **{"slots": True} if sys.version_info >= (3, 10) else {},
+ )
+ class ToVarOperation(ToOperation, cls):
+ """Base class of converting a var to another var type."""
+
+ _original: Var = dataclasses.field(
+ default=Var(_js_expr="null", _var_type=None),
+ )
+
+ _default_var_type: ClassVar[GenericType] = python_types[0]
+
+ ToVarOperation.__name__ = f'To{cls.__name__.removesuffix("Var")}Operation'
+
+ _var_subclasses.append(VarSubclassEntry(cls, ToVarOperation, python_types))
+
+ def __post_init__(self):
+ """Post-initialize the var."""
+ # Decode any inline Var markup and apply it to the instance
+ _var_data, _js_expr = _decode_var_immutable(self._js_expr)
+
+ if _var_data or _js_expr != self._js_expr:
+ self.__init__(
+ _js_expr=_js_expr,
+ _var_type=self._var_type,
+ _var_data=VarData.merge(self._var_data, _var_data),
+ )
+
+ def __hash__(self) -> int:
+ """Define a hash function for the var.
+
+ Returns:
+ The hash of the var.
+ """
+ return hash((self._js_expr, self._var_type, self._var_data))
+
+ def _get_all_var_data(self) -> VarData | None:
+ """Get all VarData associated with the Var.
+
+ Returns:
+ The VarData of the components and all of its children.
+ """
+ return self._var_data
+
+ def equals(self, other: Var) -> bool:
+ """Check if two vars are equal.
+
+ Args:
+ other: The other var to compare.
+
+ Returns:
+ Whether the vars are equal.
+ """
+ return (
+ self._js_expr == other._js_expr
+ and self._var_type == other._var_type
+ and self._get_all_var_data() == other._get_all_var_data()
+ )
+
+ @overload
+ def _replace(
+ self, _var_type: Type[OTHER_VAR_TYPE], merge_var_data=None, **kwargs: Any
+ ) -> Var[OTHER_VAR_TYPE]: ...
+
+ @overload
+ def _replace(
+ self, _var_type: GenericType | None = None, merge_var_data=None, **kwargs: Any
+ ) -> Self: ...
+
+ def _replace(
+ self, _var_type: GenericType | None = None, merge_var_data=None, **kwargs: Any
+ ) -> Self | Var:
+ """Make a copy of this Var with updated fields.
+
+ Args:
+ merge_var_data: VarData to merge into the existing VarData.
+ **kwargs: Var fields to update.
+
+ Returns:
+ A new Var with the updated fields overwriting the corresponding fields in this Var.
+
+ Raises:
+ TypeError: If _var_is_local, _var_is_string, or _var_full_name_needs_state_prefix is not None.
+ """
+ if kwargs.get("_var_is_local", False) is not False:
+ raise TypeError("The _var_is_local argument is not supported for Var.")
+
+ if kwargs.get("_var_is_string", False) is not False:
+ raise TypeError("The _var_is_string argument is not supported for Var.")
+
+ if kwargs.get("_var_full_name_needs_state_prefix", False) is not False:
+ raise TypeError(
+ "The _var_full_name_needs_state_prefix argument is not supported for Var."
+ )
+
+ value_with_replaced = dataclasses.replace(
+ self,
+ _var_type=_var_type or self._var_type,
+ _var_data=VarData.merge(
+ kwargs.get("_var_data", self._var_data), merge_var_data
+ ),
+ **kwargs,
+ )
+
+ if (js_expr := kwargs.get("_js_expr")) is not None:
+ object.__setattr__(value_with_replaced, "_js_expr", js_expr)
+
+ return value_with_replaced
+
+ @classmethod
+ def create(
+ cls,
+ value: Any,
+ _var_is_local: bool | None = None,
+ _var_is_string: bool | None = None,
+ _var_data: VarData | None = None,
+ ) -> Var:
+ """Create a var from a value.
+
+ Args:
+ value: The value to create the var from.
+ _var_is_local: Whether the var is local. Deprecated.
+ _var_is_string: Whether the var is a string literal. Deprecated.
+ _var_data: Additional hooks and imports associated with the Var.
+
+ Returns:
+ The var.
+ """
+ if _var_is_local is not None:
+ console.deprecate(
+ feature_name="_var_is_local",
+ reason="The _var_is_local argument is not supported for Var."
+ "If you want to create a Var from a raw Javascript expression, use the constructor directly",
+ deprecation_version="0.6.0",
+ removal_version="0.7.0",
+ )
+ if _var_is_string is not None:
+ console.deprecate(
+ feature_name="_var_is_string",
+ reason="The _var_is_string argument is not supported for Var."
+ "If you want to create a Var from a raw Javascript expression, use the constructor directly",
+ deprecation_version="0.6.0",
+ removal_version="0.7.0",
+ )
+
+ # If the value is already a var, do nothing.
+ if isinstance(value, Var):
+ return value
+
+ # Try to pull the imports and hooks from contained values.
+ if not isinstance(value, str):
+ return LiteralVar.create(value)
+
+ if _var_is_string is False or _var_is_local is True:
+ return cls(
+ _js_expr=value,
+ _var_data=_var_data,
+ )
+
+ return LiteralVar.create(value, _var_data=_var_data)
+
+ @classmethod
+ @deprecated("Use `.create()` instead.")
+ def create_safe(
+ cls,
+ *args: Any,
+ **kwargs: Any,
+ ) -> Var:
+ """Create a var from a value.
+
+ Args:
+ *args: The arguments to create the var from.
+ **kwargs: The keyword arguments to create the var from.
+
+ Returns:
+ The var.
+ """
+ return cls.create(*args, **kwargs)
+
+ def __format__(self, format_spec: str) -> str:
+ """Format the var into a Javascript equivalent to an f-string.
+
+ Args:
+ format_spec: The format specifier (Ignored for now).
+
+ Returns:
+ The formatted var.
+ """
+ hashed_var = hash(self)
+
+ _global_vars[hashed_var] = self
+
+ # Encode the _var_data into the formatted output for tracking purposes.
+ return f"{constants.REFLEX_VAR_OPENING_TAG}{hashed_var}{constants.REFLEX_VAR_CLOSING_TAG}{self._js_expr}"
+
+ @overload
+ def to(self, output: Type[StringVar]) -> StringVar: ...
+
+ @overload
+ def to(self, output: Type[str]) -> StringVar: ...
+
+ @overload
+ def to(self, output: Type[BooleanVar]) -> BooleanVar: ...
+
+ @overload
+ def to(
+ self, output: Type[NumberVar], var_type: type[int] | type[float] = float
+ ) -> NumberVar: ...
+
+ @overload
+ def to(
+ self,
+ output: Type[ArrayVar],
+ var_type: type[list] | type[tuple] | type[set] = list,
+ ) -> ArrayVar: ...
+
+ @overload
+ def to(
+ self, output: Type[ObjectVar], var_type: types.GenericType = dict
+ ) -> ObjectVar: ...
+
+ @overload
+ def to(
+ self, output: Type[FunctionVar], var_type: Type[Callable] = Callable
+ ) -> FunctionVar: ...
+
+ @overload
+ def to(
+ self,
+ output: Type[OUTPUT] | types.GenericType,
+ var_type: types.GenericType | None = None,
+ ) -> OUTPUT: ...
+
+ def to(
+ self,
+ output: Type[OUTPUT] | types.GenericType,
+ var_type: types.GenericType | None = None,
+ ) -> Var:
+ """Convert the var to a different type.
+
+ Args:
+ output: The output type.
+ var_type: The type of the var.
+
+ Returns:
+ The converted var.
+ """
+ from .object import ObjectVar
+
+ fixed_output_type = get_origin(output) or output
+
+ # If the first argument is a python type, we map it to the corresponding Var type.
+ for var_subclass in _var_subclasses[::-1]:
+ if fixed_output_type in var_subclass.python_types:
+ return self.to(var_subclass.var_subclass, output)
+
+ if fixed_output_type is None:
+ return get_to_operation(NoneVar).create(self) # type: ignore
+
+ # Handle fixed_output_type being Base or a dataclass.
+ try:
+ if issubclass(fixed_output_type, Base):
+ return self.to(ObjectVar, output)
+ except TypeError:
+ pass
+ if dataclasses.is_dataclass(fixed_output_type) and not issubclass(
+ fixed_output_type, Var
+ ):
+ return self.to(ObjectVar, output)
+
+ if inspect.isclass(output):
+ for var_subclass in _var_subclasses[::-1]:
+ if issubclass(output, var_subclass.var_subclass):
+ to_operation_return = var_subclass.to_var_subclass.create(
+ value=self, _var_type=var_type
+ )
+ return to_operation_return # type: ignore
+
+ # If we can't determine the first argument, we just replace the _var_type.
+ if not issubclass(output, Var) or var_type is None:
+ return dataclasses.replace(
+ self,
+ _var_type=output,
+ )
+
+ # We couldn't determine the output type to be any other Var type, so we replace the _var_type.
+ if var_type is not None:
+ return dataclasses.replace(
+ self,
+ _var_type=var_type,
+ )
+
+ return self
+
+ @overload
+ def guess_type(self: Var[str]) -> StringVar: ...
+
+ @overload
+ def guess_type(self: Var[bool]) -> BooleanVar: ...
+
+ @overload
+ def guess_type(self: Var[int] | Var[float] | Var[int | float]) -> NumberVar: ...
+
+ @overload
+ def guess_type(self) -> Self: ...
+
+ def guess_type(self) -> Var:
+ """Guesses the type of the variable based on its `_var_type` attribute.
+
+ Returns:
+ Var: The guessed type of the variable.
+
+ Raises:
+ TypeError: If the type is not supported for guessing.
+ """
+ from .number import NumberVar
+ from .object import ObjectVar
+
+ var_type = self._var_type
+ if var_type is None:
+ return self.to(None)
+ if types.is_optional(var_type):
+ var_type = types.get_args(var_type)[0]
+
+ if var_type is Any:
+ return self
+
+ fixed_type = get_origin(var_type) or var_type
+
+ if fixed_type in types.UnionTypes:
+ inner_types = get_args(var_type)
+
+ if all(
+ inspect.isclass(t) and issubclass(t, (int, float)) for t in inner_types
+ ):
+ return self.to(NumberVar, self._var_type)
+
+ if all(
+ inspect.isclass(t)
+ and (issubclass(t, Base) or dataclasses.is_dataclass(t))
+ for t in inner_types
+ ):
+ return self.to(ObjectVar, self._var_type)
+
+ return self
+
+ if fixed_type is Literal:
+ args = get_args(var_type)
+ fixed_type = unionize(*(type(arg) for arg in args))
+
+ if not inspect.isclass(fixed_type):
+ raise TypeError(f"Unsupported type {var_type} for guess_type.")
+
+ if fixed_type is None:
+ return self.to(None)
+
+ for var_subclass in _var_subclasses[::-1]:
+ if issubclass(fixed_type, var_subclass.python_types):
+ return self.to(var_subclass.var_subclass, self._var_type)
+
+ try:
+ if issubclass(fixed_type, Base):
+ return self.to(ObjectVar, self._var_type)
+ except TypeError:
+ pass
+ if dataclasses.is_dataclass(fixed_type):
+ return self.to(ObjectVar, self._var_type)
+ return self
+
+ def get_default_value(self) -> Any:
+ """Get the default value of the var.
+
+ Returns:
+ The default value of the var.
+
+ Raises:
+ ImportError: If the var is a dataframe and pandas is not installed.
+ """
+ if types.is_optional(self._var_type):
+ return None
+
+ type_ = (
+ get_origin(self._var_type)
+ if types.is_generic_alias(self._var_type)
+ else self._var_type
+ )
+ if type_ is Literal:
+ args = get_args(self._var_type)
+ return args[0] if args else None
+ if issubclass(type_, str):
+ return ""
+ if issubclass(type_, types.get_args(Union[int, float])):
+ return 0
+ if issubclass(type_, bool):
+ return False
+ if issubclass(type_, list):
+ return []
+ if issubclass(type_, dict):
+ return {}
+ if issubclass(type_, tuple):
+ return ()
+ if types.is_dataframe(type_):
+ try:
+ import pandas as pd
+
+ return pd.DataFrame()
+ except ImportError as e:
+ raise ImportError(
+ "Please install pandas to use dataframes in your app."
+ ) from e
+ return set() if issubclass(type_, set) else None
+
+ def get_setter_name(self, include_state: bool = True) -> str:
+ """Get the name of the var's generated setter function.
+
+ Args:
+ include_state: Whether to include the state name in the setter name.
+
+ Returns:
+ The name of the setter function.
+ """
+ setter = constants.SETTER_PREFIX + self._var_field_name
+ var_data = self._get_all_var_data()
+ if var_data is None:
+ return setter
+ if not include_state or var_data.state == "":
+ return setter
+ return ".".join((var_data.state, setter))
+
+ def get_setter(self) -> Callable[[BaseState, Any], None]:
+ """Get the var's setter function.
+
+ Returns:
+ A function that that creates a setter for the var.
+ """
+ actual_name = self._var_field_name
+
+ def setter(state: BaseState, value: Any):
+ """Get the setter for the var.
+
+ Args:
+ state: The state within which we add the setter function.
+ value: The value to set.
+ """
+ if self._var_type in [int, float]:
+ try:
+ value = self._var_type(value)
+ setattr(state, actual_name, value)
+ except ValueError:
+ console.debug(
+ f"{type(state).__name__}.{self._js_expr}: Failed conversion of {value} to '{self._var_type.__name__}'. Value not set.",
+ )
+ else:
+ setattr(state, actual_name, value)
+
+ setter.__qualname__ = self.get_setter_name()
+
+ return setter
+
+ def _var_set_state(self, state: type[BaseState] | str):
+ """Set the state of the var.
+
+ Args:
+ state: The state to set.
+
+ Returns:
+ The var with the state set.
+ """
+ formatted_state_name = (
+ state
+ if isinstance(state, str)
+ else format_state_name(state.get_full_name())
+ )
+
+ return StateOperation.create(
+ formatted_state_name,
+ self,
+ _var_data=VarData.merge(
+ VarData.from_state(state, self._js_expr), self._var_data
+ ),
+ ).guess_type()
+
+ def __eq__(self, other: Var | Any) -> BooleanVar:
+ """Check if the current variable is equal to the given variable.
+
+ Args:
+ other (Var | Any): The variable to compare with.
+
+ Returns:
+ BooleanVar: A BooleanVar object representing the result of the equality check.
+ """
+ from .number import equal_operation
+
+ return equal_operation(self, other)
+
+ def __ne__(self, other: Var | Any) -> BooleanVar:
+ """Check if the current object is not equal to the given object.
+
+ Parameters:
+ other (Var | Any): The object to compare with.
+
+ Returns:
+ BooleanVar: A BooleanVar object representing the result of the comparison.
+ """
+ from .number import equal_operation
+
+ return ~equal_operation(self, other)
+
+ def bool(self) -> BooleanVar:
+ """Convert the var to a boolean.
+
+ Returns:
+ The boolean var.
+ """
+ from .number import boolify
+
+ return boolify(self)
+
+ def __and__(self, other: Var | Any) -> Var:
+ """Perform a logical AND operation on the current instance and another variable.
+
+ Args:
+ other: The variable to perform the logical AND operation with.
+
+ Returns:
+ A `BooleanVar` object representing the result of the logical AND operation.
+ """
+ return and_operation(self, other)
+
+ def __rand__(self, other: Var | Any) -> Var:
+ """Perform a logical AND operation on the current instance and another variable.
+
+ Args:
+ other: The variable to perform the logical AND operation with.
+
+ Returns:
+ A `BooleanVar` object representing the result of the logical AND operation.
+ """
+ return and_operation(other, self)
+
+ def __or__(self, other: Var | Any) -> Var:
+ """Perform a logical OR operation on the current instance and another variable.
+
+ Args:
+ other: The variable to perform the logical OR operation with.
+
+ Returns:
+ A `BooleanVar` object representing the result of the logical OR operation.
+ """
+ return or_operation(self, other)
+
+ def __ror__(self, other: Var | Any) -> Var:
+ """Perform a logical OR operation on the current instance and another variable.
+
+ Args:
+ other: The variable to perform the logical OR operation with.
+
+ Returns:
+ A `BooleanVar` object representing the result of the logical OR operation.
+ """
+ return or_operation(other, self)
+
+ def __invert__(self) -> BooleanVar:
+ """Perform a logical NOT operation on the current instance.
+
+ Returns:
+ A `BooleanVar` object representing the result of the logical NOT operation.
+ """
+ return ~self.bool()
+
+ def to_string(self, use_json: bool = True) -> StringVar:
+ """Convert the var to a string.
+
+ Args:
+ use_json: Whether to use JSON stringify. If False, uses Object.prototype.toString.
+
+ Returns:
+ The string var.
+ """
+ from .function import JSON_STRINGIFY, PROTOTYPE_TO_STRING
+ from .sequence import StringVar
+
+ return (
+ JSON_STRINGIFY.call(self).to(StringVar)
+ if use_json
+ else PROTOTYPE_TO_STRING.call(self).to(StringVar)
+ )
+
+ def as_ref(self) -> Var:
+ """Get a reference to the var.
+
+ Returns:
+ The reference to the var.
+ """
+ from .object import ObjectVar
+
+ refs = Var(
+ _js_expr="refs",
+ _var_data=VarData(
+ imports={
+ f"$/{constants.Dirs.STATE_PATH}": [imports.ImportVar(tag="refs")]
+ }
+ ),
+ ).to(ObjectVar, Dict[str, str])
+ return refs[LiteralVar.create(str(self))]
+
+ @deprecated("Use `.js_type()` instead.")
+ def _type(self) -> StringVar:
+ """Returns the type of the object.
+
+ This method uses the `typeof` function from the `FunctionStringVar` class
+ to determine the type of the object.
+
+ Returns:
+ StringVar: A string variable representing the type of the object.
+ """
+ return self.js_type()
+
+ def js_type(self) -> StringVar:
+ """Returns the javascript type of the object.
+
+ This method uses the `typeof` function from the `FunctionStringVar` class
+ to determine the type of the object.
+
+ Returns:
+ StringVar: A string variable representing the type of the object.
+ """
+ from .function import FunctionStringVar
+ from .sequence import StringVar
+
+ type_of = FunctionStringVar("typeof")
+ return type_of.call(self).to(StringVar)
+
+ def without_data(self):
+ """Create a copy of the var without the data.
+
+ Returns:
+ The var without the data.
+ """
+ return dataclasses.replace(self, _var_data=None)
+
+ def contains(self, value: Any = None, field: Any = None):
+ """Get an attribute of the var.
+
+ Args:
+ value: The value to check for.
+ field: The field to check for.
+
+ Raises:
+ TypeError: If the var does not support contains check.
+ """
+ raise TypeError(
+ f"Var of type {self._var_type} does not support contains check."
+ )
+
+ def __get__(self, instance: Any, owner: Any):
+ """Get the var.
+
+ Args:
+ instance: The instance to get the var from.
+ owner: The owner of the var.
+
+ Returns:
+ The var.
+ """
+ return self
+
+ def reverse(self):
+ """Reverse the var.
+
+ Raises:
+ TypeError: If the var does not support reverse.
+ """
+ raise TypeError("Cannot reverse non-list var.")
+
+ def __getattr__(self, name: str):
+ """Get an attribute of the var.
+
+ Args:
+ name: The name of the attribute.
+
+ Returns:
+ The attribute.
+
+ Raises:
+ VarAttributeError: If the attribute does not exist.
+ TypeError: If the var type is Any.
+ """
+ if name.startswith("_"):
+ return self.__getattribute__(name)
+
+ if self._var_type is Any:
+ raise TypeError(
+ f"You must provide an annotation for the state var `{str(self)}`. Annotation cannot be `{self._var_type}`."
+ )
+
+ if name in REPLACED_NAMES:
+ raise VarAttributeError(
+ f"Field {name!r} was renamed to {REPLACED_NAMES[name]!r}"
+ )
+
+ raise VarAttributeError(
+ f"The State var has no attribute '{name}' or may have been annotated wrongly.",
+ )
+
+ def _decode(self) -> Any:
+ """Decode Var as a python value.
+
+ Note that Var with state set cannot be decoded python-side and will be
+ returned as full_name.
+
+ Returns:
+ The decoded value or the Var name.
+ """
+ if isinstance(self, LiteralVar):
+ return self._var_value # type: ignore
+ try:
+ return json.loads(str(self))
+ except ValueError:
+ try:
+ return json.loads(self.json())
+ except (ValueError, NotImplementedError):
+ return str(self)
+
+ @property
+ def _var_state(self) -> str:
+ """Compat method for getting the state.
+
+ Returns:
+ The state name associated with the var.
+ """
+ var_data = self._get_all_var_data()
+ return var_data.state if var_data else ""
+
+ @overload
+ @classmethod
+ def range(cls, stop: int | NumberVar, /) -> ArrayVar[List[int]]: ...
+
+ @overload
+ @classmethod
+ def range(
+ cls,
+ start: int | NumberVar,
+ end: int | NumberVar,
+ step: int | NumberVar = 1,
+ /,
+ ) -> ArrayVar[List[int]]: ...
+
+ @classmethod
+ def range(
+ cls,
+ first_endpoint: int | NumberVar,
+ second_endpoint: int | NumberVar | None = None,
+ step: int | NumberVar | None = None,
+ ) -> ArrayVar[List[int]]:
+ """Create a range of numbers.
+
+ Args:
+ first_endpoint: The end of the range if second_endpoint is not provided, otherwise the start of the range.
+ second_endpoint: The end of the range.
+ step: The step of the range.
+
+ Returns:
+ The range of numbers.
+ """
+ from .sequence import ArrayVar
+
+ return ArrayVar.range(first_endpoint, second_endpoint, step)
+
+ def __bool__(self) -> bool:
+ """Raise exception if using Var in a boolean context.
+
+ Raises:
+ VarTypeError: when attempting to bool-ify the Var.
+ """
+ raise VarTypeError(
+ f"Cannot convert Var {str(self)!r} to bool for use with `if`, `and`, `or`, and `not`. "
+ "Instead use `rx.cond` and bitwise operators `&` (and), `|` (or), `~` (invert)."
+ )
+
+ def __iter__(self) -> Any:
+ """Raise exception if using Var in an iterable context.
+
+ Raises:
+ VarTypeError: when attempting to iterate over the Var.
+ """
+ raise VarTypeError(
+ f"Cannot iterate over Var {str(self)!r}. Instead use `rx.foreach`."
+ )
+
+ def __contains__(self, _: Any) -> Var:
+ """Override the 'in' operator to alert the user that it is not supported.
+
+ Raises:
+ VarTypeError: the operation is not supported
+ """
+ raise VarTypeError(
+ "'in' operator not supported for Var types, use Var.contains() instead."
+ )
+
+ def json(self) -> str:
+ """Serialize the var to a JSON string.
+
+ Raises:
+ NotImplementedError: If the method is not implemented.
+ """
+ raise NotImplementedError("Var subclasses must implement the json method.")
+
+
+OUTPUT = TypeVar("OUTPUT", bound=Var)
+
+
+class ToOperation:
+ """A var operation that converts a var to another type."""
+
+ def __getattr__(self, name: str) -> Any:
+ """Get an attribute of the var.
+
+ Args:
+ name: The name of the attribute.
+
+ Returns:
+ The attribute of the var.
+ """
+ from .object import ObjectVar
+
+ if isinstance(self, ObjectVar) and name != "_js_expr":
+ return ObjectVar.__getattr__(self, name)
+ return getattr(self._original, name)
+
+ def __post_init__(self):
+ """Post initialization."""
+ object.__delattr__(self, "_js_expr")
+
+ def __hash__(self) -> int:
+ """Calculate the hash value of the object.
+
+ Returns:
+ int: The hash value of the object.
+ """
+ return hash(self._original)
+
+ def _get_all_var_data(self) -> VarData | None:
+ """Get all the var data.
+
+ Returns:
+ The var data.
+ """
+ return VarData.merge(
+ self._original._get_all_var_data(),
+ self._var_data, # type: ignore
+ )
+
+ @classmethod
+ def create(
+ cls,
+ value: Var,
+ _var_type: GenericType | None = None,
+ _var_data: VarData | None = None,
+ ):
+ """Create a ToOperation.
+
+ Args:
+ value: The value of the var.
+ _var_type: The type of the Var.
+ _var_data: Additional hooks and imports associated with the Var.
+
+ Returns:
+ The ToOperation.
+ """
+ return cls(
+ _js_expr="", # type: ignore
+ _var_data=_var_data, # type: ignore
+ _var_type=_var_type or cls._default_var_type, # type: ignore
+ _original=value, # type: ignore
+ )
+
+
+class LiteralVar(Var):
+ """Base class for immutable literal vars."""
+
+ def __init_subclass__(cls, **kwargs):
+ """Initialize the subclass.
+
+ Args:
+ **kwargs: Additional keyword arguments.
+
+ Raises:
+ TypeError: If the LiteralVar subclass does not have a corresponding Var subclass.
+ """
+ super().__init_subclass__(**kwargs)
+
+ bases = cls.__bases__
+
+ bases_normalized = [
+ base if inspect.isclass(base) else get_origin(base) for base in bases
+ ]
+
+ possible_bases = [
+ base
+ for base in bases_normalized
+ if issubclass(base, Var) and base != LiteralVar
+ ]
+
+ if not possible_bases:
+ raise TypeError(
+ f"LiteralVar subclass {cls} must have a base class that is a subclass of Var and not LiteralVar."
+ )
+
+ var_subclasses = [
+ var_subclass
+ for var_subclass in _var_subclasses
+ if var_subclass.var_subclass in possible_bases
+ ]
+
+ if not var_subclasses:
+ raise TypeError(
+ f"LiteralVar {cls} must have a base class annotated with `python_types`."
+ )
+
+ if len(var_subclasses) != 1:
+ raise TypeError(
+ f"LiteralVar {cls} must have exactly one base class annotated with `python_types`."
+ )
+
+ var_subclass = var_subclasses[0]
+
+ # Remove the old subclass, happens because __init_subclass__ is called twice
+ # for each subclass. This is because of __slots__ in dataclasses.
+ for var_literal_subclass in list(_var_literal_subclasses):
+ if var_literal_subclass[1] is var_subclass:
+ _var_literal_subclasses.remove(var_literal_subclass)
+
+ _var_literal_subclasses.append((cls, var_subclass))
+
+ @classmethod
+ def create(
+ cls,
+ value: Any,
+ _var_data: VarData | None = None,
+ ) -> Var:
+ """Create a var from a value.
+
+ Args:
+ value: The value to create the var from.
+ _var_data: Additional hooks and imports associated with the Var.
+
+ Returns:
+ The var.
+
+ Raises:
+ TypeError: If the value is not a supported type for LiteralVar.
+ """
+ from .object import LiteralObjectVar
+ from .sequence import LiteralStringVar
+
+ if isinstance(value, Var):
+ if _var_data is None:
+ return value
+ return value._replace(merge_var_data=_var_data)
+
+ for literal_subclass, var_subclass in _var_literal_subclasses[::-1]:
+ if isinstance(value, var_subclass.python_types):
+ return literal_subclass.create(value, _var_data=_var_data)
+
+ from reflex.event import EventHandler
+ from reflex.utils.format import get_event_handler_parts
+
+ if isinstance(value, EventHandler):
+ return Var(_js_expr=".".join(filter(None, get_event_handler_parts(value))))
+
+ serialized_value = serializers.serialize(value)
+ if serialized_value is not None:
+ if isinstance(serialized_value, dict):
+ return LiteralObjectVar.create(
+ serialized_value,
+ _var_type=type(value),
+ _var_data=_var_data,
+ )
+ if isinstance(serialized_value, str):
+ return LiteralStringVar.create(
+ serialized_value, _var_type=type(value), _var_data=_var_data
+ )
+ return LiteralVar.create(serialized_value, _var_data=_var_data)
+
+ if isinstance(value, Base):
+ # get the fields of the pydantic class
+ fields = value.__fields__.keys()
+ one_level_dict = {field: getattr(value, field) for field in fields}
+
+ return LiteralObjectVar.create(
+ {
+ field: value
+ for field, value in one_level_dict.items()
+ if not callable(value)
+ },
+ _var_type=type(value),
+ _var_data=_var_data,
+ )
+
+ if dataclasses.is_dataclass(value) and not isinstance(value, type):
+ return LiteralObjectVar.create(
+ {
+ k: (None if callable(v) else v)
+ for k, v in dataclasses.asdict(value).items()
+ },
+ _var_type=type(value),
+ _var_data=_var_data,
+ )
+
+ raise TypeError(
+ f"Unsupported type {type(value)} for LiteralVar. Tried to create a LiteralVar from {value}."
+ )
+
+ def __post_init__(self):
+ """Post-initialize the var."""
+
+ def json(self) -> str:
+ """Serialize the var to a JSON string.
+
+ Raises:
+ NotImplementedError: If the method is not implemented.
+ """
+ raise NotImplementedError(
+ "LiteralVar subclasses must implement the json method."
+ )
+
+
+@serializers.serializer
+def serialize_literal(value: LiteralVar):
+ """Serialize a Literal type.
+
+ Args:
+ value: The Literal to serialize.
+
+ Returns:
+ The serialized Literal.
+ """
+ return value._var_value
+
+
+def get_python_literal(value: Union[LiteralVar, Any]) -> Any | None:
+ """Get the Python literal value.
+
+ Args:
+ value: The value to get the Python literal value of.
+
+ Returns:
+ The Python literal value.
+ """
+ if isinstance(value, LiteralVar):
+ return value._var_value
+ if isinstance(value, Var):
+ return None
+ return value
+
+
+P = ParamSpec("P")
+T = TypeVar("T")
+
+
+# NoReturn is used to match CustomVarOperationReturn with no type hint.
+@overload
+def var_operation(
+ func: Callable[P, CustomVarOperationReturn[NoReturn]],
+) -> Callable[P, Var]: ...
+
+
+@overload
+def var_operation(
+ func: Callable[P, CustomVarOperationReturn[bool]],
+) -> Callable[P, BooleanVar]: ...
+
+
+NUMBER_T = TypeVar("NUMBER_T", int, float, Union[int, float])
+
+
+@overload
+def var_operation(
+ func: Callable[P, CustomVarOperationReturn[NUMBER_T]],
+) -> Callable[P, NumberVar[NUMBER_T]]: ...
+
+
+@overload
+def var_operation(
+ func: Callable[P, CustomVarOperationReturn[str]],
+) -> Callable[P, StringVar]: ...
+
+
+LIST_T = TypeVar("LIST_T", bound=Union[List[Any], Tuple, Set])
+
+
+@overload
+def var_operation(
+ func: Callable[P, CustomVarOperationReturn[LIST_T]],
+) -> Callable[P, ArrayVar[LIST_T]]: ...
+
+
+OBJECT_TYPE = TypeVar("OBJECT_TYPE", bound=Dict)
+
+
+@overload
+def var_operation(
+ func: Callable[P, CustomVarOperationReturn[OBJECT_TYPE]],
+) -> Callable[P, ObjectVar[OBJECT_TYPE]]: ...
+
+
+@overload
+def var_operation(
+ func: Callable[P, CustomVarOperationReturn[T]],
+) -> Callable[P, Var[T]]: ...
+
+
+def var_operation(
+ func: Callable[P, CustomVarOperationReturn[T]],
+) -> Callable[P, Var[T]]:
+ """Decorator for creating a var operation.
+
+ Example:
+ ```python
+ @var_operation
+ def add(a: NumberVar, b: NumberVar):
+ return custom_var_operation(f"{a} + {b}")
+ ```
+
+ Args:
+ func: The function to decorate.
+
+ Returns:
+ The decorated function.
+ """
+
+ @functools.wraps(func)
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> Var[T]:
+ func_args = list(inspect.signature(func).parameters)
+ args_vars = {
+ func_args[i]: (LiteralVar.create(arg) if not isinstance(arg, Var) else arg)
+ for i, arg in enumerate(args)
+ }
+ kwargs_vars = {
+ key: LiteralVar.create(value) if not isinstance(value, Var) else value
+ for key, value in kwargs.items()
+ }
+
+ return CustomVarOperation.create(
+ name=func.__name__,
+ args=tuple(list(args_vars.items()) + list(kwargs_vars.items())),
+ return_var=func(*args_vars.values(), **kwargs_vars), # type: ignore
+ ).guess_type()
+
+ return wrapper
+
+
+def figure_out_type(value: Any) -> types.GenericType:
+ """Figure out the type of the value.
+
+ Args:
+ value: The value to figure out the type of.
+
+ Returns:
+ The type of the value.
+ """
+ if isinstance(value, Var):
+ return value._var_type
+ type_ = type(value)
+ if has_args(type_):
+ return type_
+ if isinstance(value, list):
+ return List[unionize(*(figure_out_type(v) for v in value))]
+ if isinstance(value, set):
+ return Set[unionize(*(figure_out_type(v) for v in value))]
+ if isinstance(value, tuple):
+ return Tuple[unionize(*(figure_out_type(v) for v in value)), ...]
+ if isinstance(value, dict):
+ return Dict[
+ unionize(*(figure_out_type(k) for k in value)),
+ unionize(*(figure_out_type(v) for v in value.values())),
+ ]
+ return type(value)
+
+
+class cached_property_no_lock(functools.cached_property):
+ """A special version of functools.cached_property that does not use a lock."""
+
+ def __init__(self, func):
+ """Initialize the cached_property_no_lock.
+
+ Args:
+ func: The function to cache.
+ """
+ super().__init__(func)
+ self.lock = contextlib.nullcontext()
+
+
+class CachedVarOperation:
+ """Base class for cached var operations to lower boilerplate code."""
+
+ def __post_init__(self):
+ """Post-initialize the CachedVarOperation."""
+ object.__delattr__(self, "_js_expr")
+
+ def __getattr__(self, name: str) -> Any:
+ """Get an attribute of the var.
+
+ Args:
+ name: The name of the attribute.
+
+ Returns:
+ The attribute.
+ """
+ if name == "_js_expr":
+ return self._cached_var_name
+
+ parent_classes = inspect.getmro(self.__class__)
+
+ next_class = parent_classes[parent_classes.index(CachedVarOperation) + 1]
+
+ return next_class.__getattr__(self, name) # type: ignore
+
+ def _get_all_var_data(self) -> VarData | None:
+ """Get all VarData associated with the Var.
+
+ Returns:
+ The VarData of the components and all of its children.
+ """
+ return self._cached_get_all_var_data
+
+ @cached_property_no_lock
+ def _cached_get_all_var_data(self) -> VarData | None:
+ """Get the cached VarData.
+
+ Returns:
+ The cached VarData.
+ """
+ return VarData.merge(
+ *map(
+ lambda value: (
+ value._get_all_var_data() if isinstance(value, Var) else None
+ ),
+ map(
+ lambda field: getattr(self, field.name),
+ dataclasses.fields(self), # type: ignore
+ ),
+ ),
+ self._var_data,
+ )
+
+ def __hash__(self) -> int:
+ """Calculate the hash of the object.
+
+ Returns:
+ The hash of the object.
+ """
+ return hash(
+ (
+ self.__class__.__name__,
+ *[
+ getattr(self, field.name)
+ for field in dataclasses.fields(self) # type: ignore
+ if field.name not in ["_js_expr", "_var_data", "_var_type"]
+ ],
+ )
+ )
+
+
+def and_operation(a: Var | Any, b: Var | Any) -> Var:
+ """Perform a logical AND operation on two variables.
+
+ Args:
+ a: The first variable.
+ b: The second variable.
+
+ Returns:
+ The result of the logical AND operation.
+ """
+ return _and_operation(a, b) # type: ignore
+
+
+@var_operation
+def _and_operation(a: Var, b: Var):
+ """Perform a logical AND operation on two variables.
+
+ Args:
+ a: The first variable.
+ b: The second variable.
+
+ Returns:
+ The result of the logical AND operation.
+ """
+ return var_operation_return(
+ js_expression=f"({a} && {b})",
+ var_type=unionize(a._var_type, b._var_type),
+ )
+
+
+def or_operation(a: Var | Any, b: Var | Any) -> Var:
+ """Perform a logical OR operation on two variables.
+
+ Args:
+ a: The first variable.
+ b: The second variable.
+
+ Returns:
+ The result of the logical OR operation.
+ """
+ return _or_operation(a, b) # type: ignore
+
+
+@var_operation
+def _or_operation(a: Var, b: Var):
+ """Perform a logical OR operation on two variables.
+
+ Args:
+ a: The first variable.
+ b: The second variable.
+
+ Returns:
+ The result of the logical OR operation.
+ """
+ return var_operation_return(
+ js_expression=f"({a} || {b})",
+ var_type=unionize(a._var_type, b._var_type),
+ )
+
+
+@dataclasses.dataclass(
+ eq=False,
+ frozen=True,
+ **{"slots": True} if sys.version_info >= (3, 10) else {},
+)
+class CallableVar(Var):
+ """Decorate a Var-returning function to act as both a Var and a function.
+
+ This is used as a compatibility shim for replacing Var objects in the
+ API with functions that return a family of Var.
+ """
+
+ fn: Callable[..., Var] = dataclasses.field(
+ default_factory=lambda: lambda: Var(_js_expr="undefined")
+ )
+ original_var: Var = dataclasses.field(
+ default_factory=lambda: Var(_js_expr="undefined")
+ )
+
+ def __init__(self, fn: Callable[..., Var]):
+ """Initialize a CallableVar.
+
+ Args:
+ fn: The function to decorate (must return Var)
+ """
+ original_var = fn()
+ super(CallableVar, self).__init__(
+ _js_expr=original_var._js_expr,
+ _var_type=original_var._var_type,
+ _var_data=VarData.merge(original_var._get_all_var_data()),
+ )
+ object.__setattr__(self, "fn", fn)
+ object.__setattr__(self, "original_var", original_var)
+
+ def __call__(self, *args, **kwargs) -> Var:
+ """Call the decorated function.
+
+ Args:
+ *args: The args to pass to the function.
+ **kwargs: The kwargs to pass to the function.
+
+ Returns:
+ The Var returned from calling the function.
+ """
+ return self.fn(*args, **kwargs)
+
+ def __hash__(self) -> int:
+ """Calculate the hash of the object.
+
+ Returns:
+ The hash of the object.
+ """
+ return hash((self.__class__.__name__, self.original_var))
+
+
+RETURN_TYPE = TypeVar("RETURN_TYPE")
+
+DICT_KEY = TypeVar("DICT_KEY")
+DICT_VAL = TypeVar("DICT_VAL")
+
+LIST_INSIDE = TypeVar("LIST_INSIDE")
+
+
+class FakeComputedVarBaseClass(property):
+ """A fake base class for ComputedVar to avoid inheriting from property."""
+
+ __pydantic_run_validation__ = False
+
+
+def is_computed_var(obj: Any) -> TypeGuard[ComputedVar]:
+ """Check if the object is a ComputedVar.
+
+ Args:
+ obj: The object to check.
+
+ Returns:
+ Whether the object is a ComputedVar.
+ """
+ return isinstance(obj, FakeComputedVarBaseClass)
+
+
+@dataclasses.dataclass(
+ eq=False,
+ frozen=True,
+ **{"slots": True} if sys.version_info >= (3, 10) else {},
+)
+class ComputedVar(Var[RETURN_TYPE]):
+ """A field with computed getters."""
+
+ # Whether to track dependencies and cache computed values
+ _cache: bool = dataclasses.field(default=False)
+
+ # Whether the computed var is a backend var
+ _backend: bool = dataclasses.field(default=False)
+
+ # The initial value of the computed var
+ _initial_value: RETURN_TYPE | types.Unset = dataclasses.field(default=types.Unset())
+
+ # Explicit var dependencies to track
+ _static_deps: set[str] = dataclasses.field(default_factory=set)
+
+ # Whether var dependencies should be auto-determined
+ _auto_deps: bool = dataclasses.field(default=True)
+
+ # Interval at which the computed var should be updated
+ _update_interval: Optional[datetime.timedelta] = dataclasses.field(default=None)
+
+ _fget: Callable[[BaseState], RETURN_TYPE] = dataclasses.field(
+ default_factory=lambda: lambda _: None
+ ) # type: ignore
+
+ def __init__(
+ self,
+ fget: Callable[[BASE_STATE], RETURN_TYPE],
+ initial_value: RETURN_TYPE | types.Unset = types.Unset(),
+ cache: bool = False,
+ deps: Optional[List[Union[str, Var]]] = None,
+ auto_deps: bool = True,
+ interval: Optional[Union[int, datetime.timedelta]] = None,
+ backend: bool | None = None,
+ **kwargs,
+ ):
+ """Initialize a ComputedVar.
+
+ Args:
+ fget: The getter function.
+ initial_value: The initial value of the computed var.
+ cache: Whether to cache the computed value.
+ deps: Explicit var dependencies to track.
+ auto_deps: Whether var dependencies should be auto-determined.
+ interval: Interval at which the computed var should be updated.
+ backend: Whether the computed var is a backend var.
+ **kwargs: additional attributes to set on the instance
+
+ Raises:
+ TypeError: If the computed var dependencies are not Var instances or var names.
+ """
+ hint = kwargs.pop("return_type", None) or get_type_hints(fget).get(
+ "return", Any
+ )
+
+ if hint is Any:
+ console.deprecate(
+ "untyped-computed-var",
+ "ComputedVar should have a return type annotation.",
+ "0.6.5",
+ "0.7.0",
+ )
+
+ kwargs.setdefault("_js_expr", fget.__name__)
+ kwargs.setdefault("_var_type", hint)
+
+ Var.__init__(
+ self,
+ _js_expr=kwargs.pop("_js_expr"),
+ _var_type=kwargs.pop("_var_type"),
+ _var_data=kwargs.pop("_var_data", None),
+ )
+
+ if kwargs:
+ raise TypeError(f"Unexpected keyword arguments: {tuple(kwargs)}")
+
+ if backend is None:
+ backend = fget.__name__.startswith("_")
+
+ object.__setattr__(self, "_backend", backend)
+ object.__setattr__(self, "_initial_value", initial_value)
+ object.__setattr__(self, "_cache", cache)
+
+ if isinstance(interval, int):
+ interval = datetime.timedelta(seconds=interval)
+
+ object.__setattr__(self, "_update_interval", interval)
+
+ if deps is None:
+ deps = []
+ else:
+ for dep in deps:
+ if isinstance(dep, Var):
+ continue
+ if isinstance(dep, str) and dep != "":
+ continue
+ raise TypeError(
+ "ComputedVar dependencies must be Var instances or var names (non-empty strings)."
+ )
+ object.__setattr__(
+ self,
+ "_static_deps",
+ {dep._js_expr if isinstance(dep, Var) else dep for dep in deps},
+ )
+ object.__setattr__(self, "_auto_deps", auto_deps)
+
+ object.__setattr__(self, "_fget", fget)
+
+ @override
+ def _replace(self, merge_var_data=None, **kwargs: Any) -> Self:
+ """Replace the attributes of the ComputedVar.
+
+ Args:
+ merge_var_data: VarData to merge into the existing VarData.
+ **kwargs: Var fields to update.
+
+ Returns:
+ The new ComputedVar instance.
+
+ Raises:
+ TypeError: If kwargs contains keys that are not allowed.
+ """
+ field_values = dict(
+ fget=kwargs.pop("fget", self._fget),
+ initial_value=kwargs.pop("initial_value", self._initial_value),
+ cache=kwargs.pop("cache", self._cache),
+ deps=kwargs.pop("deps", self._static_deps),
+ auto_deps=kwargs.pop("auto_deps", self._auto_deps),
+ interval=kwargs.pop("interval", self._update_interval),
+ backend=kwargs.pop("backend", self._backend),
+ _js_expr=kwargs.pop("_js_expr", self._js_expr),
+ _var_type=kwargs.pop("_var_type", self._var_type),
+ _var_data=kwargs.pop(
+ "_var_data", VarData.merge(self._var_data, merge_var_data)
+ ),
+ )
+
+ if kwargs:
+ unexpected_kwargs = ", ".join(kwargs.keys())
+ raise TypeError(f"Unexpected keyword arguments: {unexpected_kwargs}")
+
+ return type(self)(**field_values)
+
+ @property
+ def _cache_attr(self) -> str:
+ """Get the attribute used to cache the value on the instance.
+
+ Returns:
+ An attribute name.
+ """
+ return f"__cached_{self._js_expr}"
+
+ @property
+ def _last_updated_attr(self) -> str:
+ """Get the attribute used to store the last updated timestamp.
+
+ Returns:
+ An attribute name.
+ """
+ return f"__last_updated_{self._js_expr}"
+
+ def needs_update(self, instance: BaseState) -> bool:
+ """Check if the computed var needs to be updated.
+
+ Args:
+ instance: The state instance that the computed var is attached to.
+
+ Returns:
+ True if the computed var needs to be updated, False otherwise.
+ """
+ if self._update_interval is None:
+ return False
+ last_updated = getattr(instance, self._last_updated_attr, None)
+ if last_updated is None:
+ return True
+ return datetime.datetime.now() - last_updated > self._update_interval
+
+ @overload
+ def __get__(
+ self: ComputedVar[int] | ComputedVar[float],
+ instance: None,
+ owner: Type,
+ ) -> NumberVar: ...
+
+ @overload
+ def __get__(
+ self: ComputedVar[str],
+ instance: None,
+ owner: Type,
+ ) -> StringVar: ...
+
+ @overload
+ def __get__(
+ self: ComputedVar[dict[DICT_KEY, DICT_VAL]],
+ instance: None,
+ owner: Type,
+ ) -> ObjectVar[dict[DICT_KEY, DICT_VAL]]: ...
+
+ @overload
+ def __get__(
+ self: ComputedVar[list[LIST_INSIDE]],
+ instance: None,
+ owner: Type,
+ ) -> ArrayVar[list[LIST_INSIDE]]: ...
+
+ @overload
+ def __get__(
+ self: ComputedVar[set[LIST_INSIDE]],
+ instance: None,
+ owner: Type,
+ ) -> ArrayVar[set[LIST_INSIDE]]: ...
+
+ @overload
+ def __get__(
+ self: ComputedVar[tuple[LIST_INSIDE, ...]],
+ instance: None,
+ owner: Type,
+ ) -> ArrayVar[tuple[LIST_INSIDE, ...]]: ...
+
+ @overload
+ def __get__(self, instance: None, owner: Type) -> ComputedVar[RETURN_TYPE]: ...
+
+ @overload
+ def __get__(self, instance: BaseState, owner: Type) -> RETURN_TYPE: ...
+
+ def __get__(self, instance: BaseState | None, owner):
+ """Get the ComputedVar value.
+
+ If the value is already cached on the instance, return the cached value.
+
+ Args:
+ instance: the instance of the class accessing this computed var.
+ owner: the class that this descriptor is attached to.
+
+ Returns:
+ The value of the var for the given instance.
+ """
+ if instance is None:
+ state_where_defined = owner
+ while self._js_expr in state_where_defined.inherited_vars:
+ state_where_defined = state_where_defined.get_parent_state()
+
+ field_name = (
+ format_state_name(state_where_defined.get_full_name())
+ + "."
+ + self._js_expr
+ )
+
+ return dispatch(
+ field_name,
+ var_data=VarData.from_state(state_where_defined, self._js_expr),
+ result_var_type=self._var_type,
+ existing_var=self,
+ )
+
+ if not self._cache:
+ value = self.fget(instance)
+ else:
+ # handle caching
+ if not hasattr(instance, self._cache_attr) or self.needs_update(instance):
+ # Set cache attr on state instance.
+ setattr(instance, self._cache_attr, self.fget(instance))
+ # Ensure the computed var gets serialized to redis.
+ instance._was_touched = True
+ # Set the last updated timestamp on the state instance.
+ setattr(instance, self._last_updated_attr, datetime.datetime.now())
+ value = getattr(instance, self._cache_attr)
+
+ if not _isinstance(value, self._var_type):
+ console.deprecate(
+ "mismatched-computed-var-return",
+ f"Computed var {type(instance).__name__}.{self._js_expr} returned value of type {type(value)}, "
+ f"expected {self._var_type}. This might cause unexpected behavior.",
+ "0.6.5",
+ "0.7.0",
+ )
+
+ return value
+
+ def _deps(
+ self,
+ objclass: Type,
+ obj: FunctionType | CodeType | None = None,
+ self_name: Optional[str] = None,
+ ) -> set[str]:
+ """Determine var dependencies of this ComputedVar.
+
+ Save references to attributes accessed on "self". Recursively called
+ when the function makes a method call on "self" or define comprehensions
+ or nested functions that may reference "self".
+
+ Args:
+ objclass: the class obj this ComputedVar is attached to.
+ obj: the object to disassemble (defaults to the fget function).
+ self_name: if specified, look for this name in LOAD_FAST and LOAD_DEREF instructions.
+
+ Returns:
+ A set of variable names accessed by the given obj.
+
+ Raises:
+ VarValueError: if the function references the get_state, parent_state, or substates attributes
+ (cannot track deps in a related state, only implicitly via parent state).
+ """
+ if not self._auto_deps:
+ return self._static_deps
+ d = self._static_deps.copy()
+ if obj is None:
+ fget = self._fget
+ if fget is not None:
+ obj = cast(FunctionType, fget)
+ else:
+ return set()
+ with contextlib.suppress(AttributeError):
+ # unbox functools.partial
+ obj = cast(FunctionType, obj.func) # type: ignore
+ with contextlib.suppress(AttributeError):
+ # unbox EventHandler
+ obj = cast(FunctionType, obj.fn) # type: ignore
+
+ if self_name is None and isinstance(obj, FunctionType):
+ try:
+ # the first argument to the function is the name of "self" arg
+ self_name = obj.__code__.co_varnames[0]
+ except (AttributeError, IndexError):
+ self_name = None
+ if self_name is None:
+ # cannot reference attributes on self if method takes no args
+ return set()
+
+ invalid_names = ["get_state", "parent_state", "substates", "get_substate"]
+ self_is_top_of_stack = False
+ for instruction in dis.get_instructions(obj):
+ if (
+ instruction.opname in ("LOAD_FAST", "LOAD_DEREF")
+ and instruction.argval == self_name
+ ):
+ # bytecode loaded the class instance to the top of stack, next load instruction
+ # is referencing an attribute on self
+ self_is_top_of_stack = True
+ continue
+ if self_is_top_of_stack and instruction.opname in (
+ "LOAD_ATTR",
+ "LOAD_METHOD",
+ ):
+ try:
+ ref_obj = getattr(objclass, instruction.argval)
+ except Exception:
+ ref_obj = None
+ if instruction.argval in invalid_names:
+ raise VarValueError(
+ f"Cached var {str(self)} cannot access arbitrary state via `{instruction.argval}`."
+ )
+ if callable(ref_obj):
+ # recurse into callable attributes
+ d.update(
+ self._deps(
+ objclass=objclass,
+ obj=ref_obj,
+ )
+ )
+ # recurse into property fget functions
+ elif isinstance(ref_obj, property) and not isinstance(
+ ref_obj, ComputedVar
+ ):
+ d.update(
+ self._deps(
+ objclass=objclass,
+ obj=ref_obj.fget, # type: ignore
+ )
+ )
+ elif (
+ instruction.argval in objclass.backend_vars
+ or instruction.argval in objclass.vars
+ ):
+ # var access
+ d.add(instruction.argval)
+ elif instruction.opname == "LOAD_CONST" and isinstance(
+ instruction.argval, CodeType
+ ):
+ # recurse into nested functions / comprehensions, which can reference
+ # instance attributes from the outer scope
+ d.update(
+ self._deps(
+ objclass=objclass,
+ obj=instruction.argval,
+ self_name=self_name,
+ )
+ )
+ self_is_top_of_stack = False
+ return d
+
+ def mark_dirty(self, instance) -> None:
+ """Mark this ComputedVar as dirty.
+
+ Args:
+ instance: the state instance that needs to recompute the value.
+ """
+ with contextlib.suppress(AttributeError):
+ delattr(instance, self._cache_attr)
+
+ def _determine_var_type(self) -> Type:
+ """Get the type of the var.
+
+ Returns:
+ The type of the var.
+ """
+ hints = get_type_hints(self._fget)
+ if "return" in hints:
+ return hints["return"]
+ return Any
+
+ @property
+ def __class__(self) -> Type:
+ """Get the class of the var.
+
+ Returns:
+ The class of the var.
+ """
+ return FakeComputedVarBaseClass
+
+ @property
+ def fget(self) -> Callable[[BaseState], RETURN_TYPE]:
+ """Get the getter function.
+
+ Returns:
+ The getter function.
+ """
+ return self._fget
+
+
+class DynamicRouteVar(ComputedVar[Union[str, List[str]]]):
+ """A ComputedVar that represents a dynamic route."""
+
+ pass
+
+
+if TYPE_CHECKING:
+ BASE_STATE = TypeVar("BASE_STATE", bound=BaseState)
+
+
+@overload
+def computed_var(
+ fget: None = None,
+ initial_value: Any | types.Unset = types.Unset(),
+ cache: bool = False,
+ deps: Optional[List[Union[str, Var]]] = None,
+ auto_deps: bool = True,
+ interval: Optional[Union[datetime.timedelta, int]] = None,
+ backend: bool | None = None,
+ **kwargs,
+) -> Callable[[Callable[[BASE_STATE], RETURN_TYPE]], ComputedVar[RETURN_TYPE]]: ...
+
+
+@overload
+def computed_var(
+ fget: Callable[[BASE_STATE], RETURN_TYPE],
+ initial_value: RETURN_TYPE | types.Unset = types.Unset(),
+ cache: bool = False,
+ deps: Optional[List[Union[str, Var]]] = None,
+ auto_deps: bool = True,
+ interval: Optional[Union[datetime.timedelta, int]] = None,
+ backend: bool | None = None,
+ **kwargs,
+) -> ComputedVar[RETURN_TYPE]: ...
+
+
+def computed_var(
+ fget: Callable[[BASE_STATE], Any] | None = None,
+ initial_value: Any | types.Unset = types.Unset(),
+ cache: bool = False,
+ deps: Optional[List[Union[str, Var]]] = None,
+ auto_deps: bool = True,
+ interval: Optional[Union[datetime.timedelta, int]] = None,
+ backend: bool | None = None,
+ **kwargs,
+) -> ComputedVar | Callable[[Callable[[BASE_STATE], Any]], ComputedVar]:
+ """A ComputedVar decorator with or without kwargs.
+
+ Args:
+ fget: The getter function.
+ initial_value: The initial value of the computed var.
+ cache: Whether to cache the computed value.
+ deps: Explicit var dependencies to track.
+ auto_deps: Whether var dependencies should be auto-determined.
+ interval: Interval at which the computed var should be updated.
+ backend: Whether the computed var is a backend var.
+ **kwargs: additional attributes to set on the instance
+
+ Returns:
+ A ComputedVar instance.
+
+ Raises:
+ ValueError: If caching is disabled and an update interval is set.
+ VarDependencyError: If user supplies dependencies without caching.
+ """
+ if cache is False and interval is not None:
+ raise ValueError("Cannot set update interval without caching.")
+
+ if cache is False and (deps is not None or auto_deps is False):
+ raise VarDependencyError("Cannot track dependencies without caching.")
+
+ if fget is not None:
+ return ComputedVar(fget, cache=cache)
+
+ def wrapper(fget: Callable[[BASE_STATE], Any]) -> ComputedVar:
+ return ComputedVar(
+ fget,
+ initial_value=initial_value,
+ cache=cache,
+ deps=deps,
+ auto_deps=auto_deps,
+ interval=interval,
+ backend=backend,
+ **kwargs,
+ )
+
+ return wrapper
+
+
+RETURN = TypeVar("RETURN")
+
+
+class CustomVarOperationReturn(Var[RETURN]):
+ """Base class for custom var operations."""
+
+ @classmethod
+ def create(
+ cls,
+ js_expression: str,
+ _var_type: Type[RETURN] | None = None,
+ _var_data: VarData | None = None,
+ ) -> CustomVarOperationReturn[RETURN]:
+ """Create a CustomVarOperation.
+
+ Args:
+ js_expression: The JavaScript expression to evaluate.
+ _var_type: The type of the var.
+ _var_data: Additional hooks and imports associated with the Var.
+
+ Returns:
+ The CustomVarOperation.
+ """
+ return CustomVarOperationReturn(
+ _js_expr=js_expression,
+ _var_type=_var_type or Any,
+ _var_data=_var_data,
+ )
+
+
+def var_operation_return(
+ js_expression: str,
+ var_type: Type[RETURN] | None = None,
+ var_data: VarData | None = None,
+) -> CustomVarOperationReturn[RETURN]:
+ """Shortcut for creating a CustomVarOperationReturn.
+
+ Args:
+ js_expression: The JavaScript expression to evaluate.
+ var_type: The type of the var.
+ var_data: Additional hooks and imports associated with the Var.
+
+ Returns:
+ The CustomVarOperationReturn.
+ """
+ return CustomVarOperationReturn.create(
+ js_expression,
+ var_type,
+ var_data,
+ )
+
+
+@dataclasses.dataclass(
+ eq=False,
+ frozen=True,
+ **{"slots": True} if sys.version_info >= (3, 10) else {},
+)
+class CustomVarOperation(CachedVarOperation, Var[T]):
+ """Base class for custom var operations."""
+
+ _name: str = dataclasses.field(default="")
+
+ _args: Tuple[Tuple[str, Var], ...] = dataclasses.field(default_factory=tuple)
+
+ _return: CustomVarOperationReturn[T] = dataclasses.field(
+ default_factory=lambda: CustomVarOperationReturn.create("")
+ )
+
+ @cached_property_no_lock
+ def _cached_var_name(self) -> str:
+ """Get the cached var name.
+
+ Returns:
+ The cached var name.
+ """
+ return str(self._return)
+
+ @cached_property_no_lock
+ def _cached_get_all_var_data(self) -> VarData | None:
+ """Get the cached VarData.
+
+ Returns:
+ The cached VarData.
+ """
+ return VarData.merge(
+ *map(
+ lambda arg: arg[1]._get_all_var_data(),
+ self._args,
+ ),
+ self._return._get_all_var_data(),
+ self._var_data,
+ )
+
+ @classmethod
+ def create(
+ cls,
+ name: str,
+ args: Tuple[Tuple[str, Var], ...],
+ return_var: CustomVarOperationReturn[T],
+ _var_data: VarData | None = None,
+ ) -> CustomVarOperation[T]:
+ """Create a CustomVarOperation.
+
+ Args:
+ name: The name of the operation.
+ args: The arguments to the operation.
+ return_var: The return var.
+ _var_data: Additional hooks and imports associated with the Var.
+
+ Returns:
+ The CustomVarOperation.
+ """
+ return CustomVarOperation(
+ _js_expr="",
+ _var_type=return_var._var_type,
+ _var_data=_var_data,
+ _name=name,
+ _args=args,
+ _return=return_var,
+ )
+
+
+class NoneVar(Var[None], python_types=type(None)):
+ """A var representing None."""
+
+
+@dataclasses.dataclass(
+ eq=False,
+ frozen=True,
+ **{"slots": True} if sys.version_info >= (3, 10) else {},
+)
+class LiteralNoneVar(LiteralVar, NoneVar):
+ """A var representing None."""
+
+ _var_value: None = None
+
+ def json(self) -> str:
+ """Serialize the var to a JSON string.
+
+ Returns:
+ The JSON string.
+ """
+ return "null"
+
+ @classmethod
+ def create(
+ cls,
+ value: None = None,
+ _var_data: VarData | None = None,
+ ) -> LiteralNoneVar:
+ """Create a var from a value.
+
+ Args:
+ value: The value of the var. Must be None. Existed for compatibility with LiteralVar.
+ _var_data: Additional hooks and imports associated with the Var.
+
+ Returns:
+ The var.
+ """
+ return LiteralNoneVar(
+ _js_expr="null",
+ _var_type=None,
+ _var_data=_var_data,
+ )
+
+
+def get_to_operation(var_subclass: Type[Var]) -> Type[ToOperation]:
+ """Get the ToOperation class for a given Var subclass.
+
+ Args:
+ var_subclass: The Var subclass.
+
+ Returns:
+ The ToOperation class.
+
+ Raises:
+ ValueError: If the ToOperation class cannot be found.
+ """
+ possible_classes = [
+ saved_var_subclass.to_var_subclass
+ for saved_var_subclass in _var_subclasses
+ if saved_var_subclass.var_subclass is var_subclass
+ ]
+ if not possible_classes:
+ raise ValueError(f"Could not find ToOperation for {var_subclass}.")
+ return possible_classes[0]
+
+
+@dataclasses.dataclass(
+ eq=False,
+ frozen=True,
+ **{"slots": True} if sys.version_info >= (3, 10) else {},
+)
+class StateOperation(CachedVarOperation, Var):
+ """A var operation that accesses a field on an object."""
+
+ _state_name: str = dataclasses.field(default="")
+ _field: Var = dataclasses.field(default_factory=lambda: LiteralNoneVar.create())
+
+ @cached_property_no_lock
+ def _cached_var_name(self) -> str:
+ """Get the cached var name.
+
+ Returns:
+ The cached var name.
+ """
+ return f"{str(self._state_name)}.{str(self._field)}"
+
+ def __getattr__(self, name: str) -> Any:
+ """Get an attribute of the var.
+
+ Args:
+ name: The name of the attribute.
+
+ Returns:
+ The attribute.
+ """
+ if name == "_js_expr":
+ return self._cached_var_name
+
+ return getattr(self._field, name)
+
+ @classmethod
+ def create(
+ cls,
+ state_name: str,
+ field: Var,
+ _var_data: VarData | None = None,
+ ) -> StateOperation:
+ """Create a DotOperation.
+
+ Args:
+ state_name: The name of the state.
+ field: The field of the state.
+ _var_data: Additional hooks and imports associated with the Var.
+
+ Returns:
+ The DotOperation.
+ """
+ return StateOperation(
+ _js_expr="",
+ _var_type=field._var_type,
+ _var_data=_var_data,
+ _state_name=state_name,
+ _field=field,
+ )
+
+
+def get_uuid_string_var() -> Var:
+ """Return a Var that generates a single memoized UUID via .web/utils/state.js.
+
+ useMemo with an empty dependency array ensures that the generated UUID is
+ consistent across re-renders of the component.
+
+ Returns:
+ A Var that generates a UUID at runtime.
+ """
+ from reflex.utils.imports import ImportVar
+ from reflex.vars import Var
+
+ unique_uuid_var = get_unique_variable_name()
+ unique_uuid_var_data = VarData(
+ imports={
+ f"$/{constants.Dirs.STATE_PATH}": {ImportVar(tag="generateUUID")}, # type: ignore
+ "react": "useMemo",
+ },
+ hooks={f"const {unique_uuid_var} = useMemo(generateUUID, [])": None},
+ )
+
+ return Var(
+ _js_expr=unique_uuid_var,
+ _var_type=str,
+ _var_data=unique_uuid_var_data,
+ )
+
+
+# Set of unique variable names.
+USED_VARIABLES = set()
+
+
+def get_unique_variable_name() -> str:
+ """Get a unique variable name.
+
+ Returns:
+ The unique variable name.
+ """
+ name = "".join([random.choice(string.ascii_lowercase) for _ in range(8)])
+ if name not in USED_VARIABLES:
+ USED_VARIABLES.add(name)
+ return name
+ return get_unique_variable_name()
+
+
+# Compile regex for finding reflex var tags.
+_decode_var_pattern_re = (
+ rf"{constants.REFLEX_VAR_OPENING_TAG}(.*?){constants.REFLEX_VAR_CLOSING_TAG}"
+)
+_decode_var_pattern = re.compile(_decode_var_pattern_re, flags=re.DOTALL)
+
+# Defined global immutable vars.
+_global_vars: Dict[int, Var] = {}
+
+
+def _extract_var_data(value: Iterable) -> list[VarData | None]:
+ """Extract the var imports and hooks from an iterable containing a Var.
+
+ Args:
+ value: The iterable to extract the VarData from
+
+ Returns:
+ The extracted VarDatas.
+ """
+ from reflex.style import Style
+ from reflex.vars import Var
+
+ var_datas = []
+ with contextlib.suppress(TypeError):
+ for sub in value:
+ if isinstance(sub, Var):
+ var_datas.append(sub._var_data)
+ elif not isinstance(sub, str):
+ # Recurse into dict values.
+ if hasattr(sub, "values") and callable(sub.values):
+ var_datas.extend(_extract_var_data(sub.values()))
+ # Recurse into iterable values (or dict keys).
+ var_datas.extend(_extract_var_data(sub))
+
+ # Style objects should already have _var_data.
+ if isinstance(value, Style):
+ var_datas.append(value._var_data)
+ else:
+ # Recurse when value is a dict itself.
+ values = getattr(value, "values", None)
+ if callable(values):
+ var_datas.extend(_extract_var_data(values()))
+ return var_datas
+
+
+# These names were changed in reflex 0.3.0
+REPLACED_NAMES = {
+ "full_name": "_var_full_name",
+ "name": "_js_expr",
+ "state": "_var_data.state",
+ "type_": "_var_type",
+ "is_local": "_var_is_local",
+ "is_string": "_var_is_string",
+ "set_state": "_var_set_state",
+ "deps": "_deps",
+}
+
+
+dispatchers: Dict[GenericType, Callable[[Var], Var]] = {}
+
+
+def transform(fn: Callable[[Var], Var]) -> Callable[[Var], Var]:
+ """Register a function to transform a Var.
+
+ Args:
+ fn: The function to register.
+
+ Returns:
+ The decorator.
+
+ Raises:
+ TypeError: If the return type of the function is not a Var.
+ TypeError: If the Var return type does not have a generic type.
+ ValueError: If a function for the generic type is already registered.
+ """
+ return_type = fn.__annotations__["return"]
+
+ origin = get_origin(return_type)
+
+ if origin is not Var:
+ raise TypeError(
+ f"Expected return type of {fn.__name__} to be a Var, got {origin}."
+ )
+
+ generic_args = get_args(return_type)
+
+ if not generic_args:
+ raise TypeError(
+ f"Expected Var return type of {fn.__name__} to have a generic type."
+ )
+
+ generic_type = get_origin(generic_args[0]) or generic_args[0]
+
+ if generic_type in dispatchers:
+ raise ValueError(f"Function for {generic_type} already registered.")
+
+ dispatchers[generic_type] = fn
+
+ return fn
+
+
+def generic_type_to_actual_type_map(
+ generic_type: GenericType, actual_type: GenericType
+) -> Dict[TypeVar, GenericType]:
+ """Map the generic type to the actual type.
+
+ Args:
+ generic_type: The generic type.
+ actual_type: The actual type.
+
+ Returns:
+ The mapping of type variables to actual types.
+
+ Raises:
+ TypeError: If the generic type and actual type do not match.
+ TypeError: If the number of generic arguments and actual arguments do not match.
+ """
+ generic_origin = get_origin(generic_type) or generic_type
+ actual_origin = get_origin(actual_type) or actual_type
+
+ if generic_origin is not actual_origin:
+ if isinstance(generic_origin, TypeVar):
+ return {generic_origin: actual_origin}
+ raise TypeError(
+ f"Type mismatch: expected {generic_origin}, got {actual_origin}."
+ )
+
+ generic_args = get_args(generic_type)
+ actual_args = get_args(actual_type)
+
+ if len(generic_args) != len(actual_args):
+ raise TypeError(
+ f"Number of generic arguments mismatch: expected {len(generic_args)}, got {len(actual_args)}."
+ )
+
+ # call recursively for nested generic types and merge the results
+ return {
+ k: v
+ for generic_arg, actual_arg in zip(generic_args, actual_args)
+ for k, v in generic_type_to_actual_type_map(generic_arg, actual_arg).items()
+ }
+
+
+def resolve_generic_type_with_mapping(
+ generic_type: GenericType, type_mapping: Dict[TypeVar, GenericType]
+):
+ """Resolve a generic type with a type mapping.
+
+ Args:
+ generic_type: The generic type.
+ type_mapping: The type mapping.
+
+ Returns:
+ The resolved generic type.
+ """
+ if isinstance(generic_type, TypeVar):
+ return type_mapping.get(generic_type, generic_type)
+
+ generic_origin = get_origin(generic_type) or generic_type
+
+ generic_args = get_args(generic_type)
+
+ if not generic_args:
+ return generic_type
+
+ mapping_for_older_python = {
+ list: List,
+ set: Set,
+ dict: Dict,
+ tuple: Tuple,
+ frozenset: FrozenSet,
+ }
+
+ return mapping_for_older_python.get(generic_origin, generic_origin)[
+ tuple(
+ resolve_generic_type_with_mapping(arg, type_mapping) for arg in generic_args
+ )
+ ]
+
+
+def resolve_arg_type_from_return_type(
+ arg_type: GenericType, return_type: GenericType, actual_return_type: GenericType
+) -> GenericType:
+ """Resolve the argument type from the return type.
+
+ Args:
+ arg_type: The argument type.
+ return_type: The return type.
+ actual_return_type: The requested return type.
+
+ Returns:
+ The argument type without the generics that are resolved.
+ """
+ return resolve_generic_type_with_mapping(
+ arg_type, generic_type_to_actual_type_map(return_type, actual_return_type)
+ )
+
+
+def dispatch(
+ field_name: str,
+ var_data: VarData,
+ result_var_type: GenericType,
+ existing_var: Var | None = None,
+) -> Var:
+ """Dispatch a Var to the appropriate transformation function.
+
+ Args:
+ field_name: The name of the field.
+ var_data: The VarData associated with the Var.
+ result_var_type: The type of the Var.
+ existing_var: The existing Var to transform. Optional.
+
+ Returns:
+ The transformed Var.
+
+ Raises:
+ TypeError: If the return type of the function is not a Var.
+ TypeError: If the Var return type does not have a generic type.
+ TypeError: If the first argument of the function is not a Var.
+ TypeError: If the first argument of the function does not have a generic type
+ """
+ result_origin_var_type = get_origin(result_var_type) or result_var_type
+
+ if result_origin_var_type in dispatchers:
+ fn = dispatchers[result_origin_var_type]
+ fn_first_arg_type = list(inspect.signature(fn).parameters.values())[
+ 0
+ ].annotation
+
+ fn_return = inspect.signature(fn).return_annotation
+
+ fn_return_origin = get_origin(fn_return) or fn_return
+
+ if fn_return_origin is not Var:
+ raise TypeError(
+ f"Expected return type of {fn.__name__} to be a Var, got {fn_return}."
+ )
+
+ fn_return_generic_args = get_args(fn_return)
+
+ if not fn_return_generic_args:
+ raise TypeError(f"Expected generic type of {fn_return} to be a type.")
+
+ arg_origin = get_origin(fn_first_arg_type) or fn_first_arg_type
+
+ if arg_origin is not Var:
+ raise TypeError(
+ f"Expected first argument of {fn.__name__} to be a Var, got {fn_first_arg_type}."
+ )
+
+ arg_generic_args = get_args(fn_first_arg_type)
+
+ if not arg_generic_args:
+ raise TypeError(
+ f"Expected generic type of {fn_first_arg_type} to be a type."
+ )
+
+ arg_type = arg_generic_args[0]
+ fn_return_type = fn_return_generic_args[0]
+
+ var = (
+ Var(
+ field_name,
+ _var_data=var_data,
+ _var_type=resolve_arg_type_from_return_type(
+ arg_type, fn_return_type, result_var_type
+ ),
+ ).guess_type()
+ if existing_var is None
+ else existing_var._replace(
+ _var_type=resolve_arg_type_from_return_type(
+ arg_type, fn_return_type, result_var_type
+ ),
+ _var_data=var_data,
+ _js_expr=field_name,
+ ).guess_type()
+ )
+
+ return fn(var)
+
+ if existing_var is not None:
+ return existing_var._replace(
+ _js_expr=field_name,
+ _var_data=var_data,
+ _var_type=result_var_type,
+ ).guess_type()
+ return Var(
+ field_name,
+ _var_data=var_data,
+ _var_type=result_var_type,
+ ).guess_type()
+
+
+V = TypeVar("V")
+
+
+class Field(Generic[T]):
+ """Shadow class for Var to allow for type hinting in the IDE."""
+
+ def __set__(self, instance, value: T):
+ """Set the Var.
+
+ Args:
+ instance: The instance of the class setting the Var.
+ value: The value to set the Var to.
+ """
+
+ @overload
+ def __get__(self: Field[bool], instance: None, owner) -> BooleanVar: ...
+
+ @overload
+ def __get__(self: Field[int], instance: None, owner) -> NumberVar: ...
+
+ @overload
+ def __get__(self: Field[str], instance: None, owner) -> StringVar: ...
+
+ @overload
+ def __get__(self: Field[None], instance: None, owner) -> NoneVar: ...
+
+ @overload
+ def __get__(
+ self: Field[List[V]] | Field[Set[V]] | Field[Tuple[V, ...]],
+ instance: None,
+ owner,
+ ) -> ArrayVar[List[V]]: ...
+
+ @overload
+ def __get__(
+ self: Field[Dict[str, V]], instance: None, owner
+ ) -> ObjectVar[Dict[str, V]]: ...
+
+ @overload
+ def __get__(self, instance: None, owner) -> Var[T]: ...
+
+ @overload
+ def __get__(self, instance, owner) -> T: ...
+
+ def __get__(self, instance, owner): # type: ignore
+ """Get the Var.
+
+ Args:
+ instance: The instance of the class accessing the Var.
+ owner: The class that the Var is attached to.
+ """
+
+
+def field(value: T) -> Field[T]:
+ """Create a Field with a value.
+
+ Args:
+ value: The value of the Field.
+
+ Returns:
+ The Field.
+ """
+ return value # type: ignore
diff --git a/reflex/vars/function.py b/reflex/vars/function.py
new file mode 100644
index 000000000..9d734a458
--- /dev/null
+++ b/reflex/vars/function.py
@@ -0,0 +1,186 @@
+"""Immutable function vars."""
+
+from __future__ import annotations
+
+import dataclasses
+import sys
+from typing import Any, Callable, Optional, Tuple, Type, Union
+
+from reflex.utils.types import GenericType
+
+from .base import (
+ CachedVarOperation,
+ LiteralVar,
+ Var,
+ VarData,
+ cached_property_no_lock,
+)
+
+
+class FunctionVar(Var[Callable], python_types=Callable):
+ """Base class for immutable function vars."""
+
+ def __call__(self, *args: Var | Any) -> ArgsFunctionOperation:
+ """Call the function with the given arguments.
+
+ Args:
+ *args: The arguments to call the function with.
+
+ Returns:
+ The function call operation.
+ """
+ return ArgsFunctionOperation.create(
+ ("...args",),
+ VarOperationCall.create(self, *args, Var(_js_expr="...args")),
+ )
+
+ def call(self, *args: Var | Any) -> VarOperationCall:
+ """Call the function with the given arguments.
+
+ Args:
+ *args: The arguments to call the function with.
+
+ Returns:
+ The function call operation.
+ """
+ return VarOperationCall.create(self, *args)
+
+
+class FunctionStringVar(FunctionVar):
+ """Base class for immutable function vars from a string."""
+
+ @classmethod
+ def create(
+ cls,
+ func: str,
+ _var_type: Type[Callable] = Callable,
+ _var_data: VarData | None = None,
+ ) -> FunctionStringVar:
+ """Create a new function var from a string.
+
+ Args:
+ func: The function to call.
+ _var_data: Additional hooks and imports associated with the Var.
+
+ Returns:
+ The function var.
+ """
+ return cls(
+ _js_expr=func,
+ _var_type=_var_type,
+ _var_data=_var_data,
+ )
+
+
+@dataclasses.dataclass(
+ eq=False,
+ frozen=True,
+ **{"slots": True} if sys.version_info >= (3, 10) else {},
+)
+class VarOperationCall(CachedVarOperation, Var):
+ """Base class for immutable vars that are the result of a function call."""
+
+ _func: Optional[FunctionVar] = dataclasses.field(default=None)
+ _args: Tuple[Union[Var, Any], ...] = dataclasses.field(default_factory=tuple)
+
+ @cached_property_no_lock
+ def _cached_var_name(self) -> str:
+ """The name of the var.
+
+ Returns:
+ The name of the var.
+ """
+ return f"({str(self._func)}({', '.join([str(LiteralVar.create(arg)) for arg in self._args])}))"
+
+ @cached_property_no_lock
+ def _cached_get_all_var_data(self) -> VarData | None:
+ """Get all the var data associated with the var.
+
+ Returns:
+ All the var data associated with the var.
+ """
+ return VarData.merge(
+ self._func._get_all_var_data() if self._func is not None else None,
+ *[LiteralVar.create(arg)._get_all_var_data() for arg in self._args],
+ self._var_data,
+ )
+
+ @classmethod
+ def create(
+ cls,
+ func: FunctionVar,
+ *args: Var | Any,
+ _var_type: GenericType = Any,
+ _var_data: VarData | None = None,
+ ) -> VarOperationCall:
+ """Create a new function call var.
+
+ Args:
+ func: The function to call.
+ *args: The arguments to call the function with.
+ _var_data: Additional hooks and imports associated with the Var.
+
+ Returns:
+ The function call var.
+ """
+ return cls(
+ _js_expr="",
+ _var_type=_var_type,
+ _var_data=_var_data,
+ _func=func,
+ _args=args,
+ )
+
+
+@dataclasses.dataclass(
+ eq=False,
+ frozen=True,
+ **{"slots": True} if sys.version_info >= (3, 10) else {},
+)
+class ArgsFunctionOperation(CachedVarOperation, FunctionVar):
+ """Base class for immutable function defined via arguments and return expression."""
+
+ _args_names: Tuple[str, ...] = dataclasses.field(default_factory=tuple)
+ _return_expr: Union[Var, Any] = dataclasses.field(default=None)
+
+ @cached_property_no_lock
+ def _cached_var_name(self) -> str:
+ """The name of the var.
+
+ Returns:
+ The name of the var.
+ """
+ return f"(({', '.join(self._args_names)}) => ({str(LiteralVar.create(self._return_expr))}))"
+
+ @classmethod
+ def create(
+ cls,
+ args_names: Tuple[str, ...],
+ return_expr: Var | Any,
+ _var_type: GenericType = Callable,
+ _var_data: VarData | None = None,
+ ) -> ArgsFunctionOperation:
+ """Create a new function var.
+
+ Args:
+ args_names: The names of the arguments.
+ return_expr: The return expression of the function.
+ _var_data: Additional hooks and imports associated with the Var.
+
+ Returns:
+ The function var.
+ """
+ return cls(
+ _js_expr="",
+ _var_type=_var_type,
+ _var_data=_var_data,
+ _args_names=args_names,
+ _return_expr=return_expr,
+ )
+
+
+JSON_STRINGIFY = FunctionStringVar.create("JSON.stringify")
+ARRAY_ISARRAY = FunctionStringVar.create("Array.isArray")
+PROTOTYPE_TO_STRING = FunctionStringVar.create(
+ "((__to_string) => __to_string.toString())"
+)
diff --git a/reflex/vars/number.py b/reflex/vars/number.py
new file mode 100644
index 000000000..e403e63e4
--- /dev/null
+++ b/reflex/vars/number.py
@@ -0,0 +1,1140 @@
+"""Immutable number vars."""
+
+from __future__ import annotations
+
+import dataclasses
+import json
+import math
+import sys
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ NoReturn,
+ Type,
+ TypeVar,
+ Union,
+ overload,
+)
+
+from reflex.constants.base import Dirs
+from reflex.utils.exceptions import PrimitiveUnserializableToJSON, VarTypeError
+from reflex.utils.imports import ImportDict, ImportVar
+from reflex.utils.types import is_optional
+
+from .base import (
+ CustomVarOperationReturn,
+ LiteralVar,
+ Var,
+ VarData,
+ unionize,
+ var_operation,
+ var_operation_return,
+)
+
+NUMBER_T = TypeVar("NUMBER_T", int, float, Union[int, float], bool)
+
+if TYPE_CHECKING:
+ from .sequence import ArrayVar
+
+
+def raise_unsupported_operand_types(
+ operator: str, operands_types: tuple[type, ...]
+) -> NoReturn:
+ """Raise an unsupported operand types error.
+
+ Args:
+ operator: The operator.
+ operands_types: The types of the operands.
+
+ Raises:
+ VarTypeError: The operand types are unsupported.
+ """
+ raise VarTypeError(
+ f"Unsupported Operand type(s) for {operator}: {', '.join(map(lambda t: t.__name__, operands_types))}"
+ )
+
+
+class NumberVar(Var[NUMBER_T], python_types=(int, float)):
+ """Base class for immutable number vars."""
+
+ @overload
+ def __add__(self, other: number_types) -> NumberVar: ...
+
+ @overload
+ def __add__(self, other: NoReturn) -> NoReturn: ...
+
+ def __add__(self, other: Any):
+ """Add two numbers.
+
+ Args:
+ other: The other number.
+
+ Returns:
+ The number addition operation.
+ """
+ if not isinstance(other, NUMBER_TYPES):
+ raise_unsupported_operand_types("+", (type(self), type(other)))
+ return number_add_operation(self, +other)
+
+ @overload
+ def __radd__(self, other: number_types) -> NumberVar: ...
+
+ @overload
+ def __radd__(self, other: NoReturn) -> NoReturn: ...
+
+ def __radd__(self, other: Any):
+ """Add two numbers.
+
+ Args:
+ other: The other number.
+
+ Returns:
+ The number addition operation.
+ """
+ if not isinstance(other, NUMBER_TYPES):
+ raise_unsupported_operand_types("+", (type(other), type(self)))
+ return number_add_operation(+other, self)
+
+ @overload
+ def __sub__(self, other: number_types) -> NumberVar: ...
+
+ @overload
+ def __sub__(self, other: NoReturn) -> NoReturn: ...
+
+ def __sub__(self, other: Any):
+ """Subtract two numbers.
+
+ Args:
+ other: The other number.
+
+ Returns:
+ The number subtraction operation.
+ """
+ if not isinstance(other, NUMBER_TYPES):
+ raise_unsupported_operand_types("-", (type(self), type(other)))
+
+ return number_subtract_operation(self, +other)
+
+ @overload
+ def __rsub__(self, other: number_types) -> NumberVar: ...
+
+ @overload
+ def __rsub__(self, other: NoReturn) -> NoReturn: ...
+
+ def __rsub__(self, other: Any):
+ """Subtract two numbers.
+
+ Args:
+ other: The other number.
+
+ Returns:
+ The number subtraction operation.
+ """
+ if not isinstance(other, NUMBER_TYPES):
+ raise_unsupported_operand_types("-", (type(other), type(self)))
+
+ return number_subtract_operation(+other, self)
+
+ def __abs__(self):
+ """Get the absolute value of the number.
+
+ Returns:
+ The number absolute operation.
+ """
+ return number_abs_operation(self)
+
+ @overload
+ def __mul__(self, other: number_types | boolean_types) -> NumberVar: ...
+
+ @overload
+ def __mul__(self, other: list | tuple | set | ArrayVar) -> ArrayVar: ...
+
+ def __mul__(self, other: Any):
+ """Multiply two numbers.
+
+ Args:
+ other: The other number.
+
+ Returns:
+ The number multiplication operation.
+ """
+ from .sequence import ArrayVar, LiteralArrayVar
+
+ if isinstance(other, (list, tuple, set, ArrayVar)):
+ if isinstance(other, ArrayVar):
+ return other * self
+ return LiteralArrayVar.create(other) * self
+
+ if not isinstance(other, NUMBER_TYPES):
+ raise_unsupported_operand_types("*", (type(self), type(other)))
+
+ return number_multiply_operation(self, +other)
+
+ @overload
+ def __rmul__(self, other: number_types | boolean_types) -> NumberVar: ...
+
+ @overload
+ def __rmul__(self, other: list | tuple | set | ArrayVar) -> ArrayVar: ...
+
+ def __rmul__(self, other: Any):
+ """Multiply two numbers.
+
+ Args:
+ other: The other number.
+
+ Returns:
+ The number multiplication operation.
+ """
+ from .sequence import ArrayVar, LiteralArrayVar
+
+ if isinstance(other, (list, tuple, set, ArrayVar)):
+ if isinstance(other, ArrayVar):
+ return other * self
+ return LiteralArrayVar.create(other) * self
+
+ if not isinstance(other, NUMBER_TYPES):
+ raise_unsupported_operand_types("*", (type(other), type(self)))
+
+ return number_multiply_operation(+other, self)
+
+ @overload
+ def __truediv__(self, other: number_types) -> NumberVar: ...
+
+ @overload
+ def __truediv__(self, other: NoReturn) -> NoReturn: ...
+
+ def __truediv__(self, other: Any):
+ """Divide two numbers.
+
+ Args:
+ other: The other number.
+
+ Returns:
+ The number true division operation.
+ """
+ if not isinstance(other, NUMBER_TYPES):
+ raise_unsupported_operand_types("/", (type(self), type(other)))
+
+ return number_true_division_operation(self, +other)
+
+ @overload
+ def __rtruediv__(self, other: number_types) -> NumberVar: ...
+
+ @overload
+ def __rtruediv__(self, other: NoReturn) -> NoReturn: ...
+
+ def __rtruediv__(self, other: Any):
+ """Divide two numbers.
+
+ Args:
+ other: The other number.
+
+ Returns:
+ The number true division operation.
+ """
+ if not isinstance(other, NUMBER_TYPES):
+ raise_unsupported_operand_types("/", (type(other), type(self)))
+
+ return number_true_division_operation(+other, self)
+
+ @overload
+ def __floordiv__(self, other: number_types) -> NumberVar: ...
+
+ @overload
+ def __floordiv__(self, other: NoReturn) -> NoReturn: ...
+
+ def __floordiv__(self, other: Any):
+ """Floor divide two numbers.
+
+ Args:
+ other: The other number.
+
+ Returns:
+ The number floor division operation.
+ """
+ if not isinstance(other, NUMBER_TYPES):
+ raise_unsupported_operand_types("//", (type(self), type(other)))
+
+ return number_floor_division_operation(self, +other)
+
+ @overload
+ def __rfloordiv__(self, other: number_types) -> NumberVar: ...
+
+ @overload
+ def __rfloordiv__(self, other: NoReturn) -> NoReturn: ...
+
+ def __rfloordiv__(self, other: Any):
+ """Floor divide two numbers.
+
+ Args:
+ other: The other number.
+
+ Returns:
+ The number floor division operation.
+ """
+ if not isinstance(other, NUMBER_TYPES):
+ raise_unsupported_operand_types("//", (type(other), type(self)))
+
+ return number_floor_division_operation(+other, self)
+
+ @overload
+ def __mod__(self, other: number_types) -> NumberVar: ...
+
+ @overload
+ def __mod__(self, other: NoReturn) -> NoReturn: ...
+
+ def __mod__(self, other: Any):
+ """Modulo two numbers.
+
+ Args:
+ other: The other number.
+
+ Returns:
+ The number modulo operation.
+ """
+ if not isinstance(other, NUMBER_TYPES):
+ raise_unsupported_operand_types("%", (type(self), type(other)))
+
+ return number_modulo_operation(self, +other)
+
+ @overload
+ def __rmod__(self, other: number_types) -> NumberVar: ...
+
+ @overload
+ def __rmod__(self, other: NoReturn) -> NoReturn: ...
+
+ def __rmod__(self, other: Any):
+ """Modulo two numbers.
+
+ Args:
+ other: The other number.
+
+ Returns:
+ The number modulo operation.
+ """
+ if not isinstance(other, NUMBER_TYPES):
+ raise_unsupported_operand_types("%", (type(other), type(self)))
+
+ return number_modulo_operation(+other, self)
+
+ @overload
+ def __pow__(self, other: number_types) -> NumberVar: ...
+
+ @overload
+ def __pow__(self, other: NoReturn) -> NoReturn: ...
+
+ def __pow__(self, other: Any):
+ """Exponentiate two numbers.
+
+ Args:
+ other: The other number.
+
+ Returns:
+ The number exponent operation.
+ """
+ if not isinstance(other, NUMBER_TYPES):
+ raise_unsupported_operand_types("**", (type(self), type(other)))
+
+ return number_exponent_operation(self, +other)
+
+ @overload
+ def __rpow__(self, other: number_types) -> NumberVar: ...
+
+ @overload
+ def __rpow__(self, other: NoReturn) -> NoReturn: ...
+
+ def __rpow__(self, other: Any):
+ """Exponentiate two numbers.
+
+ Args:
+ other: The other number.
+
+ Returns:
+ The number exponent operation.
+ """
+ if not isinstance(other, NUMBER_TYPES):
+ raise_unsupported_operand_types("**", (type(other), type(self)))
+
+ return number_exponent_operation(+other, self)
+
+ def __neg__(self):
+ """Negate the number.
+
+ Returns:
+ The number negation operation.
+ """
+ return number_negate_operation(self)
+
+ def __invert__(self):
+ """Boolean NOT the number.
+
+ Returns:
+ The boolean NOT operation.
+ """
+ return boolean_not_operation(self.bool())
+
+ def __pos__(self) -> NumberVar:
+ """Positive the number.
+
+ Returns:
+ The number.
+ """
+ return self
+
+ def __round__(self):
+ """Round the number.
+
+ Returns:
+ The number round operation.
+ """
+ return number_round_operation(self)
+
+ def __ceil__(self):
+ """Ceil the number.
+
+ Returns:
+ The number ceil operation.
+ """
+ return number_ceil_operation(self)
+
+ def __floor__(self):
+ """Floor the number.
+
+ Returns:
+ The number floor operation.
+ """
+ return number_floor_operation(self)
+
+ def __trunc__(self):
+ """Trunc the number.
+
+ Returns:
+ The number trunc operation.
+ """
+ return number_trunc_operation(self)
+
+ @overload
+ def __lt__(self, other: number_types) -> BooleanVar: ...
+
+ @overload
+ def __lt__(self, other: NoReturn) -> NoReturn: ...
+
+ def __lt__(self, other: Any):
+ """Less than comparison.
+
+ Args:
+ other: The other number.
+
+ Returns:
+ The result of the comparison.
+ """
+ if not isinstance(other, NUMBER_TYPES):
+ raise_unsupported_operand_types("<", (type(self), type(other)))
+ return less_than_operation(self, +other)
+
+ @overload
+ def __le__(self, other: number_types) -> BooleanVar: ...
+
+ @overload
+ def __le__(self, other: NoReturn) -> NoReturn: ...
+
+ def __le__(self, other: Any):
+ """Less than or equal comparison.
+
+ Args:
+ other: The other number.
+
+ Returns:
+ The result of the comparison.
+ """
+ if not isinstance(other, NUMBER_TYPES):
+ raise_unsupported_operand_types("<=", (type(self), type(other)))
+ return less_than_or_equal_operation(self, +other)
+
+ def __eq__(self, other: Any):
+ """Equal comparison.
+
+ Args:
+ other: The other number.
+
+ Returns:
+ The result of the comparison.
+ """
+ if isinstance(other, NUMBER_TYPES):
+ return equal_operation(self, +other)
+ return equal_operation(self, other)
+
+ def __ne__(self, other: Any):
+ """Not equal comparison.
+
+ Args:
+ other: The other number.
+
+ Returns:
+ The result of the comparison.
+ """
+ if isinstance(other, NUMBER_TYPES):
+ return not_equal_operation(self, +other)
+ return not_equal_operation(self, other)
+
+ @overload
+ def __gt__(self, other: number_types) -> BooleanVar: ...
+
+ @overload
+ def __gt__(self, other: NoReturn) -> NoReturn: ...
+
+ def __gt__(self, other: Any):
+ """Greater than comparison.
+
+ Args:
+ other: The other number.
+
+ Returns:
+ The result of the comparison.
+ """
+ if not isinstance(other, NUMBER_TYPES):
+ raise_unsupported_operand_types(">", (type(self), type(other)))
+ return greater_than_operation(self, +other)
+
+ @overload
+ def __ge__(self, other: number_types) -> BooleanVar: ...
+
+ @overload
+ def __ge__(self, other: NoReturn) -> NoReturn: ...
+
+ def __ge__(self, other: Any):
+ """Greater than or equal comparison.
+
+ Args:
+ other: The other number.
+
+ Returns:
+ The result of the comparison.
+ """
+ if not isinstance(other, NUMBER_TYPES):
+ raise_unsupported_operand_types(">=", (type(self), type(other)))
+ return greater_than_or_equal_operation(self, +other)
+
+ def bool(self):
+ """Boolean conversion.
+
+ Returns:
+ The boolean value of the number.
+ """
+ if is_optional(self._var_type):
+ return boolify((self != None) & (self != 0)) # noqa: E711
+ return self != 0
+
+ def _is_strict_float(self) -> bool:
+ """Check if the number is a float.
+
+ Returns:
+ bool: True if the number is a float.
+ """
+ return issubclass(self._var_type, float)
+
+ def _is_strict_int(self) -> bool:
+ """Check if the number is an int.
+
+ Returns:
+ bool: True if the number is an int.
+ """
+ return issubclass(self._var_type, int)
+
+
+def binary_number_operation(
+ func: Callable[[NumberVar, NumberVar], str],
+) -> Callable[[number_types, number_types], NumberVar]:
+ """Decorator to create a binary number operation.
+
+ Args:
+ func: The binary number operation function.
+
+ Returns:
+ The binary number operation.
+ """
+
+ @var_operation
+ def operation(lhs: NumberVar, rhs: NumberVar):
+ return var_operation_return(
+ js_expression=func(lhs, rhs),
+ var_type=unionize(lhs._var_type, rhs._var_type),
+ )
+
+ def wrapper(lhs: number_types, rhs: number_types) -> NumberVar:
+ """Create the binary number operation.
+
+ Args:
+ lhs: The first number.
+ rhs: The second number.
+
+ Returns:
+ The binary number operation.
+ """
+ return operation(lhs, rhs) # type: ignore
+
+ return wrapper
+
+
+@binary_number_operation
+def number_add_operation(lhs: NumberVar, rhs: NumberVar):
+ """Add two numbers.
+
+ Args:
+ lhs: The first number.
+ rhs: The second number.
+
+ Returns:
+ The number addition operation.
+ """
+ return f"({lhs} + {rhs})"
+
+
+@binary_number_operation
+def number_subtract_operation(lhs: NumberVar, rhs: NumberVar):
+ """Subtract two numbers.
+
+ Args:
+ lhs: The first number.
+ rhs: The second number.
+
+ Returns:
+ The number subtraction operation.
+ """
+ return f"({lhs} - {rhs})"
+
+
+@var_operation
+def number_abs_operation(value: NumberVar):
+ """Get the absolute value of the number.
+
+ Args:
+ value: The number.
+
+ Returns:
+ The number absolute operation.
+ """
+ return var_operation_return(
+ js_expression=f"Math.abs({value})", var_type=value._var_type
+ )
+
+
+@binary_number_operation
+def number_multiply_operation(lhs: NumberVar, rhs: NumberVar):
+ """Multiply two numbers.
+
+ Args:
+ lhs: The first number.
+ rhs: The second number.
+
+ Returns:
+ The number multiplication operation.
+ """
+ return f"({lhs} * {rhs})"
+
+
+@var_operation
+def number_negate_operation(
+ value: NumberVar[NUMBER_T],
+) -> CustomVarOperationReturn[NUMBER_T]:
+ """Negate the number.
+
+ Args:
+ value: The number.
+
+ Returns:
+ The number negation operation.
+ """
+ return var_operation_return(js_expression=f"-({value})", var_type=value._var_type)
+
+
+@binary_number_operation
+def number_true_division_operation(lhs: NumberVar, rhs: NumberVar):
+ """Divide two numbers.
+
+ Args:
+ lhs: The first number.
+ rhs: The second number.
+
+ Returns:
+ The number true division operation.
+ """
+ return f"({lhs} / {rhs})"
+
+
+@binary_number_operation
+def number_floor_division_operation(lhs: NumberVar, rhs: NumberVar):
+ """Floor divide two numbers.
+
+ Args:
+ lhs: The first number.
+ rhs: The second number.
+
+ Returns:
+ The number floor division operation.
+ """
+ return f"Math.floor({lhs} / {rhs})"
+
+
+@binary_number_operation
+def number_modulo_operation(lhs: NumberVar, rhs: NumberVar):
+ """Modulo two numbers.
+
+ Args:
+ lhs: The first number.
+ rhs: The second number.
+
+ Returns:
+ The number modulo operation.
+ """
+ return f"({lhs} % {rhs})"
+
+
+@binary_number_operation
+def number_exponent_operation(lhs: NumberVar, rhs: NumberVar):
+ """Exponentiate two numbers.
+
+ Args:
+ lhs: The first number.
+ rhs: The second number.
+
+ Returns:
+ The number exponent operation.
+ """
+ return f"({lhs} ** {rhs})"
+
+
+@var_operation
+def number_round_operation(value: NumberVar):
+ """Round the number.
+
+ Args:
+ value: The number.
+
+ Returns:
+ The number round operation.
+ """
+ return var_operation_return(js_expression=f"Math.round({value})", var_type=int)
+
+
+@var_operation
+def number_ceil_operation(value: NumberVar):
+ """Ceil the number.
+
+ Args:
+ value: The number.
+
+ Returns:
+ The number ceil operation.
+ """
+ return var_operation_return(js_expression=f"Math.ceil({value})", var_type=int)
+
+
+@var_operation
+def number_floor_operation(value: NumberVar):
+ """Floor the number.
+
+ Args:
+ value: The number.
+
+ Returns:
+ The number floor operation.
+ """
+ return var_operation_return(js_expression=f"Math.floor({value})", var_type=int)
+
+
+@var_operation
+def number_trunc_operation(value: NumberVar):
+ """Trunc the number.
+
+ Args:
+ value: The number.
+
+ Returns:
+ The number trunc operation.
+ """
+ return var_operation_return(js_expression=f"Math.trunc({value})", var_type=int)
+
+
+class BooleanVar(NumberVar[bool], python_types=bool):
+ """Base class for immutable boolean vars."""
+
+ def __invert__(self):
+ """NOT the boolean.
+
+ Returns:
+ The boolean NOT operation.
+ """
+ return boolean_not_operation(self)
+
+ def __int__(self):
+ """Convert the boolean to an int.
+
+ Returns:
+ The boolean to int operation.
+ """
+ return boolean_to_number_operation(self)
+
+ def __pos__(self):
+ """Convert the boolean to an int.
+
+ Returns:
+ The boolean to int operation.
+ """
+ return boolean_to_number_operation(self)
+
+ def bool(self) -> BooleanVar:
+ """Boolean conversion.
+
+ Returns:
+ The boolean value of the boolean.
+ """
+ return self
+
+ def __lt__(self, other: Any):
+ """Less than comparison.
+
+ Args:
+ other: The other boolean.
+
+ Returns:
+ The result of the comparison.
+ """
+ return +self < other
+
+ def __le__(self, other: Any):
+ """Less than or equal comparison.
+
+ Args:
+ other: The other boolean.
+
+ Returns:
+ The result of the comparison.
+ """
+ return +self <= other
+
+ def __gt__(self, other: Any):
+ """Greater than comparison.
+
+ Args:
+ other: The other boolean.
+
+ Returns:
+ The result of the comparison.
+ """
+ return +self > other
+
+ def __ge__(self, other: Any):
+ """Greater than or equal comparison.
+
+ Args:
+ other: The other boolean.
+
+ Returns:
+ The result of the comparison.
+ """
+ return +self >= other
+
+
+@var_operation
+def boolean_to_number_operation(value: BooleanVar):
+ """Convert the boolean to a number.
+
+ Args:
+ value: The boolean.
+
+ Returns:
+ The boolean to number operation.
+ """
+ return var_operation_return(js_expression=f"Number({value})", var_type=int)
+
+
+def comparison_operator(
+ func: Callable[[Var, Var], str],
+) -> Callable[[Var | Any, Var | Any], BooleanVar]:
+ """Decorator to create a comparison operation.
+
+ Args:
+ func: The comparison operation function.
+
+ Returns:
+ The comparison operation.
+ """
+
+ @var_operation
+ def operation(lhs: Var, rhs: Var):
+ return var_operation_return(
+ js_expression=func(lhs, rhs),
+ var_type=bool,
+ )
+
+ def wrapper(lhs: Var | Any, rhs: Var | Any) -> BooleanVar:
+ """Create the comparison operation.
+
+ Args:
+ lhs: The first value.
+ rhs: The second value.
+
+ Returns:
+ The comparison operation.
+ """
+ return operation(lhs, rhs)
+
+ return wrapper
+
+
+@comparison_operator
+def greater_than_operation(lhs: Var, rhs: Var):
+ """Greater than comparison.
+
+ Args:
+ lhs: The first value.
+ rhs: The second value.
+
+ Returns:
+ The result of the comparison.
+ """
+ return f"({lhs} > {rhs})"
+
+
+@comparison_operator
+def greater_than_or_equal_operation(lhs: Var, rhs: Var):
+ """Greater than or equal comparison.
+
+ Args:
+ lhs: The first value.
+ rhs: The second value.
+
+ Returns:
+ The result of the comparison.
+ """
+ return f"({lhs} >= {rhs})"
+
+
+@comparison_operator
+def less_than_operation(lhs: Var, rhs: Var):
+ """Less than comparison.
+
+ Args:
+ lhs: The first value.
+ rhs: The second value.
+
+ Returns:
+ The result of the comparison.
+ """
+ return f"({lhs} < {rhs})"
+
+
+@comparison_operator
+def less_than_or_equal_operation(lhs: Var, rhs: Var):
+ """Less than or equal comparison.
+
+ Args:
+ lhs: The first value.
+ rhs: The second value.
+
+ Returns:
+ The result of the comparison.
+ """
+ return f"({lhs} <= {rhs})"
+
+
+@comparison_operator
+def equal_operation(lhs: Var, rhs: Var):
+ """Equal comparison.
+
+ Args:
+ lhs: The first value.
+ rhs: The second value.
+
+ Returns:
+ The result of the comparison.
+ """
+ return f"({lhs} === {rhs})"
+
+
+@comparison_operator
+def not_equal_operation(lhs: Var, rhs: Var):
+ """Not equal comparison.
+
+ Args:
+ lhs: The first value.
+ rhs: The second value.
+
+ Returns:
+ The result of the comparison.
+ """
+ return f"({lhs} !== {rhs})"
+
+
+@var_operation
+def boolean_not_operation(value: BooleanVar):
+ """Boolean NOT the boolean.
+
+ Args:
+ value: The boolean.
+
+ Returns:
+ The boolean NOT operation.
+ """
+ return var_operation_return(js_expression=f"!({value})", var_type=bool)
+
+
+@dataclasses.dataclass(
+ eq=False,
+ frozen=True,
+ **{"slots": True} if sys.version_info >= (3, 10) else {},
+)
+class LiteralNumberVar(LiteralVar, NumberVar):
+ """Base class for immutable literal number vars."""
+
+ _var_value: float | int = dataclasses.field(default=0)
+
+ def json(self) -> str:
+ """Get the JSON representation of the var.
+
+ Returns:
+ The JSON representation of the var.
+
+ Raises:
+ PrimitiveUnserializableToJSON: If the var is unserializable to JSON.
+ """
+ if math.isinf(self._var_value) or math.isnan(self._var_value):
+ raise PrimitiveUnserializableToJSON(
+ f"No valid JSON representation for {self}"
+ )
+ return json.dumps(self._var_value)
+
+ def __hash__(self) -> int:
+ """Calculate the hash value of the object.
+
+ Returns:
+ int: The hash value of the object.
+ """
+ return hash((self.__class__.__name__, self._var_value))
+
+ @classmethod
+ def create(cls, value: float | int, _var_data: VarData | None = None):
+ """Create the number var.
+
+ Args:
+ value: The value of the var.
+ _var_data: Additional hooks and imports associated with the Var.
+
+ Returns:
+ The number var.
+ """
+ if math.isinf(value):
+ js_expr = "Infinity" if value > 0 else "-Infinity"
+ elif math.isnan(value):
+ js_expr = "NaN"
+ else:
+ js_expr = str(value)
+
+ return cls(
+ _js_expr=js_expr,
+ _var_type=type(value),
+ _var_data=_var_data,
+ _var_value=value,
+ )
+
+
+@dataclasses.dataclass(
+ eq=False,
+ frozen=True,
+ **{"slots": True} if sys.version_info >= (3, 10) else {},
+)
+class LiteralBooleanVar(LiteralVar, BooleanVar):
+ """Base class for immutable literal boolean vars."""
+
+ _var_value: bool = dataclasses.field(default=False)
+
+ def json(self) -> str:
+ """Get the JSON representation of the var.
+
+ Returns:
+ The JSON representation of the var.
+ """
+ return "true" if self._var_value else "false"
+
+ def __hash__(self) -> int:
+ """Calculate the hash value of the object.
+
+ Returns:
+ int: The hash value of the object.
+ """
+ return hash((self.__class__.__name__, self._var_value))
+
+ @classmethod
+ def create(cls, value: bool, _var_data: VarData | None = None):
+ """Create the boolean var.
+
+ Args:
+ value: The value of the var.
+ _var_data: Additional hooks and imports associated with the Var.
+
+ Returns:
+ The boolean var.
+ """
+ return cls(
+ _js_expr="true" if value else "false",
+ _var_type=bool,
+ _var_data=_var_data,
+ _var_value=value,
+ )
+
+
+number_types = Union[NumberVar, int, float]
+boolean_types = Union[BooleanVar, bool]
+
+
+_IS_TRUE_IMPORT: ImportDict = {
+ f"$/{Dirs.STATE_PATH}": [ImportVar(tag="isTrue")],
+}
+
+
+@var_operation
+def boolify(value: Var):
+ """Convert the value to a boolean.
+
+ Args:
+ value: The value.
+
+ Returns:
+ The boolean value.
+ """
+ return var_operation_return(
+ js_expression=f"isTrue({value})",
+ var_type=bool,
+ var_data=VarData(imports=_IS_TRUE_IMPORT),
+ )
+
+
+T = TypeVar("T")
+U = TypeVar("U")
+
+
+@var_operation
+def ternary_operation(condition: BooleanVar, if_true: Var[T], if_false: Var[U]):
+ """Create a ternary operation.
+
+ Args:
+ condition: The condition.
+ if_true: The value if the condition is true.
+ if_false: The value if the condition is false.
+
+ Returns:
+ The ternary operation.
+ """
+ type_value: Union[Type[T], Type[U]] = unionize(
+ if_true._var_type, if_false._var_type
+ )
+ value: CustomVarOperationReturn[Union[T, U]] = var_operation_return(
+ js_expression=f"({condition} ? {if_true} : {if_false})",
+ var_type=type_value,
+ )
+ return value
+
+
+NUMBER_TYPES = (int, float, NumberVar)
diff --git a/reflex/vars/object.py b/reflex/vars/object.py
new file mode 100644
index 000000000..56f3535d8
--- /dev/null
+++ b/reflex/vars/object.py
@@ -0,0 +1,536 @@
+"""Classes for immutable object vars."""
+
+from __future__ import annotations
+
+import dataclasses
+import sys
+import typing
+from inspect import isclass
+from typing import (
+ Any,
+ Dict,
+ List,
+ NoReturn,
+ Tuple,
+ Type,
+ TypeVar,
+ Union,
+ get_args,
+ overload,
+)
+
+from reflex.utils import types
+from reflex.utils.exceptions import VarAttributeError
+from reflex.utils.types import GenericType, get_attribute_access_type, get_origin
+
+from .base import (
+ CachedVarOperation,
+ LiteralVar,
+ Var,
+ VarData,
+ cached_property_no_lock,
+ figure_out_type,
+ var_operation,
+ var_operation_return,
+)
+from .number import BooleanVar, NumberVar, raise_unsupported_operand_types
+from .sequence import ArrayVar, StringVar
+
+OBJECT_TYPE = TypeVar("OBJECT_TYPE", bound=Dict)
+
+KEY_TYPE = TypeVar("KEY_TYPE")
+VALUE_TYPE = TypeVar("VALUE_TYPE")
+
+ARRAY_INNER_TYPE = TypeVar("ARRAY_INNER_TYPE")
+
+OTHER_KEY_TYPE = TypeVar("OTHER_KEY_TYPE")
+
+
+class ObjectVar(Var[OBJECT_TYPE], python_types=dict):
+ """Base class for immutable object vars."""
+
+ def _key_type(self) -> Type:
+ """Get the type of the keys of the object.
+
+ Returns:
+ The type of the keys of the object.
+ """
+ return str
+
+ @overload
+ def _value_type(
+ self: ObjectVar[Dict[KEY_TYPE, VALUE_TYPE]],
+ ) -> Type[VALUE_TYPE]: ...
+
+ @overload
+ def _value_type(self) -> Type: ...
+
+ def _value_type(self) -> Type:
+ """Get the type of the values of the object.
+
+ Returns:
+ The type of the values of the object.
+ """
+ fixed_type = get_origin(self._var_type) or self._var_type
+ if not isclass(fixed_type):
+ return Any
+ args = get_args(self._var_type) if issubclass(fixed_type, dict) else ()
+ return args[1] if args else Any
+
+ def keys(self) -> ArrayVar[List[str]]:
+ """Get the keys of the object.
+
+ Returns:
+ The keys of the object.
+ """
+ return object_keys_operation(self)
+
+ @overload
+ def values(
+ self: ObjectVar[Dict[KEY_TYPE, VALUE_TYPE]],
+ ) -> ArrayVar[List[VALUE_TYPE]]: ...
+
+ @overload
+ def values(self) -> ArrayVar: ...
+
+ def values(self) -> ArrayVar:
+ """Get the values of the object.
+
+ Returns:
+ The values of the object.
+ """
+ return object_values_operation(self)
+
+ @overload
+ def entries(
+ self: ObjectVar[Dict[KEY_TYPE, VALUE_TYPE]],
+ ) -> ArrayVar[List[Tuple[str, VALUE_TYPE]]]: ...
+
+ @overload
+ def entries(self) -> ArrayVar: ...
+
+ def entries(self) -> ArrayVar:
+ """Get the entries of the object.
+
+ Returns:
+ The entries of the object.
+ """
+ return object_entries_operation(self)
+
+ items = entries
+
+ def merge(self, other: ObjectVar):
+ """Merge two objects.
+
+ Args:
+ other: The other object to merge.
+
+ Returns:
+ The merged object.
+ """
+ return object_merge_operation(self, other)
+
+ # NoReturn is used here to catch when key value is Any
+ @overload
+ def __getitem__(
+ self: ObjectVar[Dict[KEY_TYPE, NoReturn]],
+ key: Var | Any,
+ ) -> Var: ...
+
+ @overload
+ def __getitem__(
+ self: (
+ ObjectVar[Dict[KEY_TYPE, int]]
+ | ObjectVar[Dict[KEY_TYPE, float]]
+ | ObjectVar[Dict[KEY_TYPE, int | float]]
+ ),
+ key: Var | Any,
+ ) -> NumberVar: ...
+
+ @overload
+ def __getitem__(
+ self: ObjectVar[Dict[KEY_TYPE, str]],
+ key: Var | Any,
+ ) -> StringVar: ...
+
+ @overload
+ def __getitem__(
+ self: ObjectVar[Dict[KEY_TYPE, list[ARRAY_INNER_TYPE]]],
+ key: Var | Any,
+ ) -> ArrayVar[list[ARRAY_INNER_TYPE]]: ...
+
+ @overload
+ def __getitem__(
+ self: ObjectVar[Dict[KEY_TYPE, set[ARRAY_INNER_TYPE]]],
+ key: Var | Any,
+ ) -> ArrayVar[set[ARRAY_INNER_TYPE]]: ...
+
+ @overload
+ def __getitem__(
+ self: ObjectVar[Dict[KEY_TYPE, tuple[ARRAY_INNER_TYPE, ...]]],
+ key: Var | Any,
+ ) -> ArrayVar[tuple[ARRAY_INNER_TYPE, ...]]: ...
+
+ @overload
+ def __getitem__(
+ self: ObjectVar[Dict[KEY_TYPE, dict[OTHER_KEY_TYPE, VALUE_TYPE]]],
+ key: Var | Any,
+ ) -> ObjectVar[dict[OTHER_KEY_TYPE, VALUE_TYPE]]: ...
+
+ def __getitem__(self, key: Var | Any) -> Var:
+ """Get an item from the object.
+
+ Args:
+ key: The key to get from the object.
+
+ Returns:
+ The item from the object.
+ """
+ if not isinstance(key, (StringVar, str, int, NumberVar)) or (
+ isinstance(key, NumberVar) and key._is_strict_float()
+ ):
+ raise_unsupported_operand_types("[]", (type(self), type(key)))
+ return ObjectItemOperation.create(self, key).guess_type()
+
+ # NoReturn is used here to catch when key value is Any
+ @overload
+ def __getattr__(
+ self: ObjectVar[Dict[KEY_TYPE, NoReturn]],
+ name: str,
+ ) -> Var: ...
+
+ @overload
+ def __getattr__(
+ self: (
+ ObjectVar[Dict[KEY_TYPE, int]]
+ | ObjectVar[Dict[KEY_TYPE, float]]
+ | ObjectVar[Dict[KEY_TYPE, int | float]]
+ ),
+ name: str,
+ ) -> NumberVar: ...
+
+ @overload
+ def __getattr__(
+ self: ObjectVar[Dict[KEY_TYPE, str]],
+ name: str,
+ ) -> StringVar: ...
+
+ @overload
+ def __getattr__(
+ self: ObjectVar[Dict[KEY_TYPE, list[ARRAY_INNER_TYPE]]],
+ name: str,
+ ) -> ArrayVar[list[ARRAY_INNER_TYPE]]: ...
+
+ @overload
+ def __getattr__(
+ self: ObjectVar[Dict[KEY_TYPE, set[ARRAY_INNER_TYPE]]],
+ name: str,
+ ) -> ArrayVar[set[ARRAY_INNER_TYPE]]: ...
+
+ @overload
+ def __getattr__(
+ self: ObjectVar[Dict[KEY_TYPE, tuple[ARRAY_INNER_TYPE, ...]]],
+ name: str,
+ ) -> ArrayVar[tuple[ARRAY_INNER_TYPE, ...]]: ...
+
+ @overload
+ def __getattr__(
+ self: ObjectVar[Dict[KEY_TYPE, dict[OTHER_KEY_TYPE, VALUE_TYPE]]],
+ name: str,
+ ) -> ObjectVar[dict[OTHER_KEY_TYPE, VALUE_TYPE]]: ...
+
+ def __getattr__(self, name) -> Var:
+ """Get an attribute of the var.
+
+ Args:
+ name: The name of the attribute.
+
+ Raises:
+ VarAttributeError: The State var has no such attribute or may have been annotated wrongly.
+
+ Returns:
+ The attribute of the var.
+ """
+ if name.startswith("__") and name.endswith("__"):
+ return getattr(super(type(self), self), name)
+
+ var_type = self._var_type
+
+ if types.is_optional(var_type):
+ var_type = get_args(var_type)[0]
+
+ fixed_type = var_type if isclass(var_type) else get_origin(var_type)
+ if (isclass(fixed_type) and not issubclass(fixed_type, dict)) or (
+ fixed_type in types.UnionTypes
+ ):
+ attribute_type = get_attribute_access_type(var_type, name)
+ if attribute_type is None:
+ raise VarAttributeError(
+ f"The State var `{str(self)}` has no attribute '{name}' or may have been annotated "
+ f"wrongly."
+ )
+ return ObjectItemOperation.create(self, name, attribute_type).guess_type()
+ else:
+ return ObjectItemOperation.create(self, name).guess_type()
+
+ def contains(self, key: Var | Any) -> BooleanVar:
+ """Check if the object contains a key.
+
+ Args:
+ key: The key to check.
+
+ Returns:
+ The result of the check.
+ """
+ return object_has_own_property_operation(self, key)
+
+
+@dataclasses.dataclass(
+ eq=False,
+ frozen=True,
+ **{"slots": True} if sys.version_info >= (3, 10) else {},
+)
+class LiteralObjectVar(CachedVarOperation, ObjectVar[OBJECT_TYPE], LiteralVar):
+ """Base class for immutable literal object vars."""
+
+ _var_value: Dict[Union[Var, Any], Union[Var, Any]] = dataclasses.field(
+ default_factory=dict
+ )
+
+ def _key_type(self) -> Type:
+ """Get the type of the keys of the object.
+
+ Returns:
+ The type of the keys of the object.
+ """
+ args_list = typing.get_args(self._var_type)
+ return args_list[0] if args_list else Any
+
+ def _value_type(self) -> Type:
+ """Get the type of the values of the object.
+
+ Returns:
+ The type of the values of the object.
+ """
+ args_list = typing.get_args(self._var_type)
+ return args_list[1] if args_list else Any
+
+ @cached_property_no_lock
+ def _cached_var_name(self) -> str:
+ """The name of the var.
+
+ Returns:
+ The name of the var.
+ """
+ return (
+ "({ "
+ + ", ".join(
+ [
+ f"[{str(LiteralVar.create(key))}] : {str(LiteralVar.create(value))}"
+ for key, value in self._var_value.items()
+ ]
+ )
+ + " })"
+ )
+
+ def json(self) -> str:
+ """Get the JSON representation of the object.
+
+ Returns:
+ The JSON representation of the object.
+ """
+ return (
+ "{"
+ + ", ".join(
+ [
+ f"{LiteralVar.create(key).json()}:{LiteralVar.create(value).json()}"
+ for key, value in self._var_value.items()
+ ]
+ )
+ + "}"
+ )
+
+ def __hash__(self) -> int:
+ """Get the hash of the var.
+
+ Returns:
+ The hash of the var.
+ """
+ return hash((self.__class__.__name__, self._js_expr))
+
+ @cached_property_no_lock
+ def _cached_get_all_var_data(self) -> VarData | None:
+ """Get all the var data.
+
+ Returns:
+ The var data.
+ """
+ return VarData.merge(
+ *[LiteralVar.create(var)._get_all_var_data() for var in self._var_value],
+ *[
+ LiteralVar.create(var)._get_all_var_data()
+ for var in self._var_value.values()
+ ],
+ self._var_data,
+ )
+
+ @classmethod
+ def create(
+ cls,
+ _var_value: OBJECT_TYPE,
+ _var_type: GenericType | None = None,
+ _var_data: VarData | None = None,
+ ) -> LiteralObjectVar[OBJECT_TYPE]:
+ """Create the literal object var.
+
+ Args:
+ _var_value: The value of the var.
+ _var_type: The type of the var.
+ _var_data: Additional hooks and imports associated with the Var.
+
+ Returns:
+ The literal object var.
+ """
+ return LiteralObjectVar(
+ _js_expr="",
+ _var_type=(figure_out_type(_var_value) if _var_type is None else _var_type),
+ _var_data=_var_data,
+ _var_value=_var_value,
+ )
+
+
+@var_operation
+def object_keys_operation(value: ObjectVar):
+ """Get the keys of an object.
+
+ Args:
+ value: The object to get the keys from.
+
+ Returns:
+ The keys of the object.
+ """
+ return var_operation_return(
+ js_expression=f"Object.keys({value})",
+ var_type=List[str],
+ )
+
+
+@var_operation
+def object_values_operation(value: ObjectVar):
+ """Get the values of an object.
+
+ Args:
+ value: The object to get the values from.
+
+ Returns:
+ The values of the object.
+ """
+ return var_operation_return(
+ js_expression=f"Object.values({value})",
+ var_type=List[value._value_type()],
+ )
+
+
+@var_operation
+def object_entries_operation(value: ObjectVar):
+ """Get the entries of an object.
+
+ Args:
+ value: The object to get the entries from.
+
+ Returns:
+ The entries of the object.
+ """
+ return var_operation_return(
+ js_expression=f"Object.entries({value})",
+ var_type=List[Tuple[str, value._value_type()]],
+ )
+
+
+@var_operation
+def object_merge_operation(lhs: ObjectVar, rhs: ObjectVar):
+ """Merge two objects.
+
+ Args:
+ lhs: The first object to merge.
+ rhs: The second object to merge.
+
+ Returns:
+ The merged object.
+ """
+ return var_operation_return(
+ js_expression=f"({{...{lhs}, ...{rhs}}})",
+ var_type=Dict[
+ Union[lhs._key_type(), rhs._key_type()],
+ Union[lhs._value_type(), rhs._value_type()],
+ ],
+ )
+
+
+@dataclasses.dataclass(
+ eq=False,
+ frozen=True,
+ **{"slots": True} if sys.version_info >= (3, 10) else {},
+)
+class ObjectItemOperation(CachedVarOperation, Var):
+ """Operation to get an item from an object."""
+
+ _object: ObjectVar = dataclasses.field(
+ default_factory=lambda: LiteralObjectVar.create({})
+ )
+ _key: Var | Any = dataclasses.field(default_factory=lambda: LiteralVar.create(None))
+
+ @cached_property_no_lock
+ def _cached_var_name(self) -> str:
+ """The name of the operation.
+
+ Returns:
+ The name of the operation.
+ """
+ if types.is_optional(self._object._var_type):
+ return f"{str(self._object)}?.[{str(self._key)}]"
+ return f"{str(self._object)}[{str(self._key)}]"
+
+ @classmethod
+ def create(
+ cls,
+ object: ObjectVar,
+ key: Var | Any,
+ _var_type: GenericType | None = None,
+ _var_data: VarData | None = None,
+ ) -> ObjectItemOperation:
+ """Create the object item operation.
+
+ Args:
+ object: The object to get the item from.
+ key: The key to get from the object.
+ _var_type: The type of the item.
+ _var_data: Additional hooks and imports associated with the operation.
+
+ Returns:
+ The object item operation.
+ """
+ return cls(
+ _js_expr="",
+ _var_type=object._value_type() if _var_type is None else _var_type,
+ _var_data=_var_data,
+ _object=object,
+ _key=key if isinstance(key, Var) else LiteralVar.create(key),
+ )
+
+
+@var_operation
+def object_has_own_property_operation(object: ObjectVar, key: Var):
+ """Check if an object has a key.
+
+ Args:
+ object: The object to check.
+ key: The key to check.
+
+ Returns:
+ The result of the check.
+ """
+ return var_operation_return(
+ js_expression=f"{object}.hasOwnProperty({key})",
+ var_type=bool,
+ )
diff --git a/reflex/vars/sequence.py b/reflex/vars/sequence.py
new file mode 100644
index 000000000..39139ce3f
--- /dev/null
+++ b/reflex/vars/sequence.py
@@ -0,0 +1,1789 @@
+"""Collection of string classes and utilities."""
+
+from __future__ import annotations
+
+import dataclasses
+import inspect
+import json
+import re
+import sys
+import typing
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Dict,
+ List,
+ Literal,
+ NoReturn,
+ Set,
+ Tuple,
+ Type,
+ Union,
+ overload,
+)
+
+from typing_extensions import TypeVar
+
+from reflex import constants
+from reflex.constants.base import REFLEX_VAR_OPENING_TAG
+from reflex.constants.colors import Color
+from reflex.utils.exceptions import VarTypeError
+from reflex.utils.types import GenericType, get_origin
+
+from .base import (
+ CachedVarOperation,
+ CustomVarOperationReturn,
+ LiteralVar,
+ Var,
+ VarData,
+ _global_vars,
+ cached_property_no_lock,
+ figure_out_type,
+ get_python_literal,
+ get_unique_variable_name,
+ unionize,
+ var_operation,
+ var_operation_return,
+)
+from .number import (
+ BooleanVar,
+ LiteralNumberVar,
+ NumberVar,
+ raise_unsupported_operand_types,
+ ternary_operation,
+)
+
+if TYPE_CHECKING:
+ from .object import ObjectVar
+
+STRING_TYPE = TypeVar("STRING_TYPE", default=str)
+
+
+class StringVar(Var[STRING_TYPE], python_types=str):
+ """Base class for immutable string vars."""
+
+ @overload
+ def __add__(self, other: StringVar | str) -> ConcatVarOperation: ...
+
+ @overload
+ def __add__(self, other: NoReturn) -> NoReturn: ...
+
+ def __add__(self, other: Any) -> ConcatVarOperation:
+ """Concatenate two strings.
+
+ Args:
+ other: The other string.
+
+ Returns:
+ The string concatenation operation.
+ """
+ if not isinstance(other, (StringVar, str)):
+ raise_unsupported_operand_types("+", (type(self), type(other)))
+
+ return ConcatVarOperation.create(self, other)
+
+ @overload
+ def __radd__(self, other: StringVar | str) -> ConcatVarOperation: ...
+
+ @overload
+ def __radd__(self, other: NoReturn) -> NoReturn: ...
+
+ def __radd__(self, other: Any) -> ConcatVarOperation:
+ """Concatenate two strings.
+
+ Args:
+ other: The other string.
+
+ Returns:
+ The string concatenation operation.
+ """
+ if not isinstance(other, (StringVar, str)):
+ raise_unsupported_operand_types("+", (type(other), type(self)))
+
+ return ConcatVarOperation.create(other, self)
+
+ @overload
+ def __mul__(self, other: NumberVar | int) -> StringVar: ...
+
+ @overload
+ def __mul__(self, other: NoReturn) -> NoReturn: ...
+
+ def __mul__(self, other: Any) -> StringVar:
+ """Multiply the sequence by a number or an integer.
+
+ Args:
+ other: The number or integer to multiply the sequence by.
+
+ Returns:
+ StringVar: The resulting sequence after multiplication.
+ """
+ if not isinstance(other, (NumberVar, int)):
+ raise_unsupported_operand_types("*", (type(self), type(other)))
+
+ return (self.split() * other).join()
+
+ @overload
+ def __rmul__(self, other: NumberVar | int) -> StringVar: ...
+
+ @overload
+ def __rmul__(self, other: NoReturn) -> NoReturn: ...
+
+ def __rmul__(self, other: Any) -> StringVar:
+ """Multiply the sequence by a number or an integer.
+
+ Args:
+ other: The number or integer to multiply the sequence by.
+
+ Returns:
+ StringVar: The resulting sequence after multiplication.
+ """
+ if not isinstance(other, (NumberVar, int)):
+ raise_unsupported_operand_types("*", (type(other), type(self)))
+
+ return (self.split() * other).join()
+
+ @overload
+ def __getitem__(self, i: slice) -> StringVar: ...
+
+ @overload
+ def __getitem__(self, i: int | NumberVar) -> StringVar: ...
+
+ def __getitem__(self, i: Any) -> StringVar:
+ """Get a slice of the string.
+
+ Args:
+ i: The slice.
+
+ Returns:
+ The string slice operation.
+ """
+ if isinstance(i, slice):
+ return self.split()[i].join()
+ if not isinstance(i, (int, NumberVar)) or (
+ isinstance(i, NumberVar) and i._is_strict_float()
+ ):
+ raise_unsupported_operand_types("[]", (type(self), type(i)))
+ return string_item_operation(self, i)
+
+ def length(self) -> NumberVar:
+ """Get the length of the string.
+
+ Returns:
+ The string length operation.
+ """
+ return self.split().length()
+
+ def lower(self) -> StringVar:
+ """Convert the string to lowercase.
+
+ Returns:
+ The string lower operation.
+ """
+ return string_lower_operation(self)
+
+ def upper(self) -> StringVar:
+ """Convert the string to uppercase.
+
+ Returns:
+ The string upper operation.
+ """
+ return string_upper_operation(self)
+
+ def strip(self) -> StringVar:
+ """Strip the string.
+
+ Returns:
+ The string strip operation.
+ """
+ return string_strip_operation(self)
+
+ def reversed(self) -> StringVar:
+ """Reverse the string.
+
+ Returns:
+ The string reverse operation.
+ """
+ return self.split().reverse().join()
+
+ @overload
+ def contains(
+ self, other: StringVar | str, field: StringVar | str | None = None
+ ) -> BooleanVar: ...
+
+ @overload
+ def contains(
+ self, other: NoReturn, field: StringVar | str | None = None
+ ) -> NoReturn: ...
+
+ def contains(self, other: Any, field: Any = None) -> BooleanVar:
+ """Check if the string contains another string.
+
+ Args:
+ other: The other string.
+ field: The field to check.
+
+ Returns:
+ The string contains operation.
+ """
+ if not isinstance(other, (StringVar, str)):
+ raise_unsupported_operand_types("contains", (type(self), type(other)))
+ if field is not None:
+ if not isinstance(field, (StringVar, str)):
+ raise_unsupported_operand_types("contains", (type(self), type(field)))
+ return string_contains_field_operation(self, other, field)
+ return string_contains_operation(self, other)
+
+ @overload
+ def split(self, separator: StringVar | str = "") -> ArrayVar[List[str]]: ...
+
+ @overload
+ def split(self, separator: NoReturn) -> NoReturn: ...
+
+ def split(self, separator: Any = "") -> ArrayVar[List[str]]:
+ """Split the string.
+
+ Args:
+ separator: The separator.
+
+ Returns:
+ The string split operation.
+ """
+ if not isinstance(separator, (StringVar, str)):
+ raise_unsupported_operand_types("split", (type(self), type(separator)))
+ return string_split_operation(self, separator)
+
+ @overload
+ def startswith(self, prefix: StringVar | str) -> BooleanVar: ...
+
+ @overload
+ def startswith(self, prefix: NoReturn) -> NoReturn: ...
+
+ def startswith(self, prefix: Any) -> BooleanVar:
+ """Check if the string starts with a prefix.
+
+ Args:
+ prefix: The prefix.
+
+ Returns:
+ The string starts with operation.
+ """
+ if not isinstance(prefix, (StringVar, str)):
+ raise_unsupported_operand_types("startswith", (type(self), type(prefix)))
+ return string_starts_with_operation(self, prefix)
+
+ @overload
+ def __lt__(self, other: StringVar | str) -> BooleanVar: ...
+
+ @overload
+ def __lt__(self, other: NoReturn) -> NoReturn: ...
+
+ def __lt__(self, other: Any):
+ """Check if the string is less than another string.
+
+ Args:
+ other: The other string.
+
+ Returns:
+ The string less than operation.
+ """
+ if not isinstance(other, (StringVar, str)):
+ raise_unsupported_operand_types("<", (type(self), type(other)))
+
+ return string_lt_operation(self, other)
+
+ @overload
+ def __gt__(self, other: StringVar | str) -> BooleanVar: ...
+
+ @overload
+ def __gt__(self, other: NoReturn) -> NoReturn: ...
+
+ def __gt__(self, other: Any):
+ """Check if the string is greater than another string.
+
+ Args:
+ other: The other string.
+
+ Returns:
+ The string greater than operation.
+ """
+ if not isinstance(other, (StringVar, str)):
+ raise_unsupported_operand_types(">", (type(self), type(other)))
+
+ return string_gt_operation(self, other)
+
+ @overload
+ def __le__(self, other: StringVar | str) -> BooleanVar: ...
+
+ @overload
+ def __le__(self, other: NoReturn) -> NoReturn: ...
+
+ def __le__(self, other: Any):
+ """Check if the string is less than or equal to another string.
+
+ Args:
+ other: The other string.
+
+ Returns:
+ The string less than or equal operation.
+ """
+ if not isinstance(other, (StringVar, str)):
+ raise_unsupported_operand_types("<=", (type(self), type(other)))
+
+ return string_le_operation(self, other)
+
+ @overload
+ def __ge__(self, other: StringVar | str) -> BooleanVar: ...
+
+ @overload
+ def __ge__(self, other: NoReturn) -> NoReturn: ...
+
+ def __ge__(self, other: Any):
+ """Check if the string is greater than or equal to another string.
+
+ Args:
+ other: The other string.
+
+ Returns:
+ The string greater than or equal operation.
+ """
+ if not isinstance(other, (StringVar, str)):
+ raise_unsupported_operand_types(">=", (type(self), type(other)))
+
+ return string_ge_operation(self, other)
+
+
+@var_operation
+def string_lt_operation(lhs: StringVar[Any] | str, rhs: StringVar[Any] | str):
+ """Check if a string is less than another string.
+
+ Args:
+ lhs: The left-hand side string.
+ rhs: The right-hand side string.
+
+ Returns:
+ The string less than operation.
+ """
+ return var_operation_return(js_expression=f"{lhs} < {rhs}", var_type=bool)
+
+
+@var_operation
+def string_gt_operation(lhs: StringVar[Any] | str, rhs: StringVar[Any] | str):
+ """Check if a string is greater than another string.
+
+ Args:
+ lhs: The left-hand side string.
+ rhs: The right-hand side string.
+
+ Returns:
+ The string greater than operation.
+ """
+ return var_operation_return(js_expression=f"{lhs} > {rhs}", var_type=bool)
+
+
+@var_operation
+def string_le_operation(lhs: StringVar[Any] | str, rhs: StringVar[Any] | str):
+ """Check if a string is less than or equal to another string.
+
+ Args:
+ lhs: The left-hand side string.
+ rhs: The right-hand side string.
+
+ Returns:
+ The string less than or equal operation.
+ """
+ return var_operation_return(js_expression=f"{lhs} <= {rhs}", var_type=bool)
+
+
+@var_operation
+def string_ge_operation(lhs: StringVar[Any] | str, rhs: StringVar[Any] | str):
+ """Check if a string is greater than or equal to another string.
+
+ Args:
+ lhs: The left-hand side string.
+ rhs: The right-hand side string.
+
+ Returns:
+ The string greater than or equal operation.
+ """
+ return var_operation_return(js_expression=f"{lhs} >= {rhs}", var_type=bool)
+
+
+@var_operation
+def string_lower_operation(string: StringVar[Any]):
+ """Convert a string to lowercase.
+
+ Args:
+ string: The string to convert.
+
+ Returns:
+ The lowercase string.
+ """
+ return var_operation_return(js_expression=f"{string}.toLowerCase()", var_type=str)
+
+
+@var_operation
+def string_upper_operation(string: StringVar[Any]):
+ """Convert a string to uppercase.
+
+ Args:
+ string: The string to convert.
+
+ Returns:
+ The uppercase string.
+ """
+ return var_operation_return(js_expression=f"{string}.toUpperCase()", var_type=str)
+
+
+@var_operation
+def string_strip_operation(string: StringVar[Any]):
+ """Strip a string.
+
+ Args:
+ string: The string to strip.
+
+ Returns:
+ The stripped string.
+ """
+ return var_operation_return(js_expression=f"{string}.trim()", var_type=str)
+
+
+@var_operation
+def string_contains_field_operation(
+ haystack: StringVar[Any], needle: StringVar[Any] | str, field: StringVar[Any] | str
+):
+ """Check if a string contains another string.
+
+ Args:
+ haystack: The haystack.
+ needle: The needle.
+ field: The field to check.
+
+ Returns:
+ The string contains operation.
+ """
+ return var_operation_return(
+ js_expression=f"{haystack}.some(obj => obj[{field}] === {needle})",
+ var_type=bool,
+ )
+
+
+@var_operation
+def string_contains_operation(haystack: StringVar[Any], needle: StringVar[Any] | str):
+ """Check if a string contains another string.
+
+ Args:
+ haystack: The haystack.
+ needle: The needle.
+
+ Returns:
+ The string contains operation.
+ """
+ return var_operation_return(
+ js_expression=f"{haystack}.includes({needle})", var_type=bool
+ )
+
+
+@var_operation
+def string_starts_with_operation(
+ full_string: StringVar[Any], prefix: StringVar[Any] | str
+):
+ """Check if a string starts with a prefix.
+
+ Args:
+ full_string: The full string.
+ prefix: The prefix.
+
+ Returns:
+ Whether the string starts with the prefix.
+ """
+ return var_operation_return(
+ js_expression=f"{full_string}.startsWith({prefix})", var_type=bool
+ )
+
+
+@var_operation
+def string_item_operation(string: StringVar[Any], index: NumberVar | int):
+ """Get an item from a string.
+
+ Args:
+ string: The string.
+ index: The index of the item.
+
+ Returns:
+ The item from the string.
+ """
+ return var_operation_return(js_expression=f"{string}.at({index})", var_type=str)
+
+
+@var_operation
+def array_join_operation(array: ArrayVar, sep: StringVar[Any] | str = ""):
+ """Join the elements of an array.
+
+ Args:
+ array: The array.
+ sep: The separator.
+
+ Returns:
+ The joined elements.
+ """
+ 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}"
+)
+_decode_var_pattern = re.compile(_decode_var_pattern_re, flags=re.DOTALL)
+
+
+@dataclasses.dataclass(
+ eq=False,
+ frozen=True,
+ **{"slots": True} if sys.version_info >= (3, 10) else {},
+)
+class LiteralStringVar(LiteralVar, StringVar[str]):
+ """Base class for immutable literal string vars."""
+
+ _var_value: str = dataclasses.field(default="")
+
+ @classmethod
+ def create(
+ cls,
+ value: str,
+ _var_type: GenericType | None = None,
+ _var_data: VarData | None = None,
+ ) -> StringVar:
+ """Create a var from a string value.
+
+ Args:
+ value: The value to create the var from.
+ _var_type: The type of the var.
+ _var_data: Additional hooks and imports associated with the Var.
+
+ Returns:
+ The var.
+ """
+ # Determine var type in case the value is inherited from str.
+ _var_type = _var_type or type(value) or str
+
+ if REFLEX_VAR_OPENING_TAG in value:
+ strings_and_vals: list[Var | str] = []
+ offset = 0
+
+ # Find all tags
+ while m := _decode_var_pattern.search(value):
+ start, end = m.span()
+
+ strings_and_vals.append(value[:start])
+
+ serialized_data = m.group(1)
+
+ if serialized_data.isnumeric() or (
+ serialized_data[0] == "-" and serialized_data[1:].isnumeric()
+ ):
+ # This is a global immutable var.
+ var = _global_vars[int(serialized_data)]
+ strings_and_vals.append(var)
+ value = value[(end + len(var._js_expr)) :]
+
+ offset += end - start
+
+ strings_and_vals.append(value)
+
+ filtered_strings_and_vals = [
+ s for s in strings_and_vals if isinstance(s, Var) or s
+ ]
+ if len(filtered_strings_and_vals) == 1:
+ only_string = filtered_strings_and_vals[0]
+ if isinstance(only_string, str):
+ return LiteralVar.create(only_string).to(StringVar, _var_type)
+ else:
+ return only_string.to(StringVar, only_string._var_type)
+
+ if len(
+ literal_strings := [
+ s
+ for s in filtered_strings_and_vals
+ if isinstance(s, (str, LiteralStringVar))
+ ]
+ ) == len(filtered_strings_and_vals):
+ return LiteralStringVar.create(
+ "".join(
+ s._var_value if isinstance(s, LiteralStringVar) else s
+ for s in literal_strings
+ ),
+ _var_type=_var_type,
+ _var_data=VarData.merge(
+ _var_data,
+ *(
+ s._get_all_var_data()
+ for s in filtered_strings_and_vals
+ if isinstance(s, Var)
+ ),
+ ),
+ )
+
+ concat_result = ConcatVarOperation.create(
+ *filtered_strings_and_vals,
+ _var_data=_var_data,
+ )
+
+ return (
+ concat_result
+ if _var_type is str
+ else concat_result.to(StringVar, _var_type)
+ )
+
+ return LiteralStringVar(
+ _js_expr=json.dumps(value),
+ _var_type=_var_type,
+ _var_data=_var_data,
+ _var_value=value,
+ )
+
+ def __hash__(self) -> int:
+ """Get the hash of the var.
+
+ Returns:
+ The hash of the var.
+ """
+ return hash((self.__class__.__name__, self._var_value))
+
+ def json(self) -> str:
+ """Get the JSON representation of the var.
+
+ Returns:
+ The JSON representation of the var.
+ """
+ return json.dumps(self._var_value)
+
+
+@dataclasses.dataclass(
+ eq=False,
+ frozen=True,
+ **{"slots": True} if sys.version_info >= (3, 10) else {},
+)
+class ConcatVarOperation(CachedVarOperation, StringVar[str]):
+ """Representing a concatenation of literal string vars."""
+
+ _var_value: Tuple[Var, ...] = dataclasses.field(default_factory=tuple)
+
+ @cached_property_no_lock
+ def _cached_var_name(self) -> str:
+ """The name of the var.
+
+ Returns:
+ The name of the var.
+ """
+ list_of_strs: List[Union[str, Var]] = []
+ last_string = ""
+ for var in self._var_value:
+ if isinstance(var, LiteralStringVar):
+ last_string += var._var_value
+ else:
+ if last_string:
+ list_of_strs.append(last_string)
+ last_string = ""
+ list_of_strs.append(var)
+
+ if last_string:
+ list_of_strs.append(last_string)
+
+ list_of_strs_filtered = [
+ str(LiteralVar.create(s)) for s in list_of_strs if isinstance(s, Var) or s
+ ]
+
+ if len(list_of_strs_filtered) == 1:
+ return list_of_strs_filtered[0]
+
+ return "(" + "+".join(list_of_strs_filtered) + ")"
+
+ @cached_property_no_lock
+ def _cached_get_all_var_data(self) -> VarData | None:
+ """Get all the VarData asVarDatae Var.
+
+ Returns:
+ The VarData associated with the Var.
+ """
+ return VarData.merge(
+ *[
+ var._get_all_var_data()
+ for var in self._var_value
+ if isinstance(var, Var)
+ ],
+ self._var_data,
+ )
+
+ @classmethod
+ def create(
+ cls,
+ *value: Var | str,
+ _var_data: VarData | None = None,
+ ) -> ConcatVarOperation:
+ """Create a var from a string value.
+
+ Args:
+ value: The values to concatenate.
+ _var_data: Additional hooks and imports associated with the Var.
+
+ Returns:
+ The var.
+ """
+ return cls(
+ _js_expr="",
+ _var_type=str,
+ _var_data=_var_data,
+ _var_value=tuple(map(LiteralVar.create, value)),
+ )
+
+
+ARRAY_VAR_TYPE = TypeVar("ARRAY_VAR_TYPE", bound=Union[List, Tuple, Set])
+
+OTHER_TUPLE = TypeVar("OTHER_TUPLE")
+
+INNER_ARRAY_VAR = TypeVar("INNER_ARRAY_VAR")
+
+KEY_TYPE = TypeVar("KEY_TYPE")
+VALUE_TYPE = TypeVar("VALUE_TYPE")
+
+
+class ArrayVar(Var[ARRAY_VAR_TYPE], python_types=(list, tuple, set)):
+ """Base class for immutable array vars."""
+
+ @overload
+ def join(self, sep: StringVar | str = "") -> StringVar: ...
+
+ @overload
+ def join(self, sep: NoReturn) -> NoReturn: ...
+
+ def join(self, sep: Any = "") -> StringVar:
+ """Join the elements of the array.
+
+ Args:
+ sep: The separator between elements.
+
+ Returns:
+ The joined elements.
+ """
+ if not isinstance(sep, (StringVar, str)):
+ raise_unsupported_operand_types("join", (type(self), type(sep)))
+ if (
+ isinstance(self, LiteralArrayVar)
+ and (
+ len(
+ args := [
+ x
+ for x in self._var_value
+ if isinstance(x, (LiteralStringVar, str))
+ ]
+ )
+ == len(self._var_value)
+ )
+ and isinstance(sep, (LiteralStringVar, str))
+ ):
+ sep_str = sep._var_value if isinstance(sep, LiteralStringVar) else sep
+ return LiteralStringVar.create(
+ sep_str.join(
+ i._var_value if isinstance(i, LiteralStringVar) else i for i in args
+ )
+ )
+ return array_join_operation(self, sep)
+
+ def reverse(self) -> ArrayVar[ARRAY_VAR_TYPE]:
+ """Reverse the array.
+
+ Returns:
+ The reversed array.
+ """
+ return array_reverse_operation(self)
+
+ @overload
+ def __add__(self, other: ArrayVar[ARRAY_VAR_TYPE]) -> ArrayVar[ARRAY_VAR_TYPE]: ...
+
+ @overload
+ def __add__(self, other: NoReturn) -> NoReturn: ...
+
+ def __add__(self, other: Any) -> ArrayVar[ARRAY_VAR_TYPE]:
+ """Concatenate two arrays.
+
+ Parameters:
+ other: The other array to concatenate.
+
+ Returns:
+ ArrayConcatOperation: The concatenation of the two arrays.
+ """
+ if not isinstance(other, ArrayVar):
+ raise_unsupported_operand_types("+", (type(self), type(other)))
+
+ return array_concat_operation(self, other)
+
+ @overload
+ def __getitem__(self, i: slice) -> ArrayVar[ARRAY_VAR_TYPE]: ...
+
+ @overload
+ def __getitem__(
+ self: (
+ ArrayVar[Tuple[int, OTHER_TUPLE]]
+ | ArrayVar[Tuple[float, OTHER_TUPLE]]
+ | ArrayVar[Tuple[int | float, OTHER_TUPLE]]
+ ),
+ i: Literal[0, -2],
+ ) -> NumberVar: ...
+
+ @overload
+ def __getitem__(
+ self: (
+ ArrayVar[Tuple[OTHER_TUPLE, int]]
+ | ArrayVar[Tuple[OTHER_TUPLE, float]]
+ | ArrayVar[Tuple[OTHER_TUPLE, int | float]]
+ ),
+ i: Literal[1, -1],
+ ) -> NumberVar: ...
+
+ @overload
+ def __getitem__(
+ self: ArrayVar[Tuple[str, OTHER_TUPLE]], i: Literal[0, -2]
+ ) -> StringVar: ...
+
+ @overload
+ def __getitem__(
+ self: ArrayVar[Tuple[OTHER_TUPLE, str]], i: Literal[1, -1]
+ ) -> StringVar: ...
+
+ @overload
+ def __getitem__(
+ self: ArrayVar[Tuple[bool, OTHER_TUPLE]], i: Literal[0, -2]
+ ) -> BooleanVar: ...
+
+ @overload
+ def __getitem__(
+ self: ArrayVar[Tuple[OTHER_TUPLE, bool]], i: Literal[1, -1]
+ ) -> BooleanVar: ...
+
+ @overload
+ def __getitem__(
+ self: (
+ ARRAY_VAR_OF_LIST_ELEMENT[int]
+ | ARRAY_VAR_OF_LIST_ELEMENT[float]
+ | ARRAY_VAR_OF_LIST_ELEMENT[int | float]
+ ),
+ i: int | NumberVar,
+ ) -> NumberVar: ...
+
+ @overload
+ def __getitem__(
+ self: ARRAY_VAR_OF_LIST_ELEMENT[str], i: int | NumberVar
+ ) -> StringVar: ...
+
+ @overload
+ def __getitem__(
+ self: ARRAY_VAR_OF_LIST_ELEMENT[bool], i: int | NumberVar
+ ) -> BooleanVar: ...
+
+ @overload
+ def __getitem__(
+ self: ARRAY_VAR_OF_LIST_ELEMENT[List[INNER_ARRAY_VAR]],
+ i: int | NumberVar,
+ ) -> ArrayVar[List[INNER_ARRAY_VAR]]: ...
+
+ @overload
+ def __getitem__(
+ self: ARRAY_VAR_OF_LIST_ELEMENT[Set[INNER_ARRAY_VAR]],
+ i: int | NumberVar,
+ ) -> ArrayVar[Set[INNER_ARRAY_VAR]]: ...
+
+ @overload
+ def __getitem__(
+ self: ARRAY_VAR_OF_LIST_ELEMENT[Tuple[KEY_TYPE, VALUE_TYPE]],
+ i: int | NumberVar,
+ ) -> ArrayVar[Tuple[KEY_TYPE, VALUE_TYPE]]: ...
+
+ @overload
+ def __getitem__(
+ self: ARRAY_VAR_OF_LIST_ELEMENT[Tuple[INNER_ARRAY_VAR, ...]],
+ i: int | NumberVar,
+ ) -> ArrayVar[Tuple[INNER_ARRAY_VAR, ...]]: ...
+
+ @overload
+ def __getitem__(
+ self: ARRAY_VAR_OF_LIST_ELEMENT[Dict[KEY_TYPE, VALUE_TYPE]],
+ i: int | NumberVar,
+ ) -> ObjectVar[Dict[KEY_TYPE, VALUE_TYPE]]: ...
+
+ @overload
+ def __getitem__(self, i: int | NumberVar) -> Var: ...
+
+ def __getitem__(self, i: Any) -> ArrayVar[ARRAY_VAR_TYPE] | Var:
+ """Get a slice of the array.
+
+ Args:
+ i: The slice.
+
+ Returns:
+ The array slice operation.
+ """
+ if isinstance(i, slice):
+ return ArraySliceOperation.create(self, i)
+ if not isinstance(i, (int, NumberVar)) or (
+ isinstance(i, NumberVar) and i._is_strict_float()
+ ):
+ raise_unsupported_operand_types("[]", (type(self), type(i)))
+ return array_item_operation(self, i)
+
+ def length(self) -> NumberVar:
+ """Get the length of the array.
+
+ Returns:
+ The length of the array.
+ """
+ return array_length_operation(self)
+
+ @overload
+ @classmethod
+ def range(cls, stop: int | NumberVar, /) -> ArrayVar[List[int]]: ...
+
+ @overload
+ @classmethod
+ def range(
+ cls,
+ start: int | NumberVar,
+ end: int | NumberVar,
+ step: int | NumberVar = 1,
+ /,
+ ) -> ArrayVar[List[int]]: ...
+
+ @overload
+ @classmethod
+ def range(
+ cls,
+ first_endpoint: int | NumberVar,
+ second_endpoint: int | NumberVar | None = None,
+ step: int | NumberVar | None = None,
+ ) -> ArrayVar[List[int]]: ...
+
+ @classmethod
+ def range(
+ cls,
+ first_endpoint: int | NumberVar,
+ second_endpoint: int | NumberVar | None = None,
+ step: int | NumberVar | None = None,
+ ) -> ArrayVar[List[int]]:
+ """Create a range of numbers.
+
+ Args:
+ first_endpoint: The end of the range if second_endpoint is not provided, otherwise the start of the range.
+ second_endpoint: The end of the range.
+ step: The step of the range.
+
+ Returns:
+ The range of numbers.
+ """
+ if any(
+ not isinstance(i, (int, NumberVar))
+ for i in (first_endpoint, second_endpoint, step)
+ if i is not None
+ ):
+ raise_unsupported_operand_types(
+ "range", (type(first_endpoint), type(second_endpoint), type(step))
+ )
+ if second_endpoint is None:
+ start = 0
+ end = first_endpoint
+ else:
+ start = first_endpoint
+ end = second_endpoint
+
+ return array_range_operation(start, end, step or 1)
+
+ @overload
+ def contains(self, other: Any) -> BooleanVar: ...
+
+ @overload
+ def contains(self, other: Any, field: StringVar | str) -> BooleanVar: ...
+
+ def contains(self, other: Any, field: Any = None) -> BooleanVar:
+ """Check if the array contains an element.
+
+ Args:
+ other: The element to check for.
+ field: The field to check.
+
+ Returns:
+ The array contains operation.
+ """
+ if field is not None:
+ if not isinstance(field, (StringVar, str)):
+ raise_unsupported_operand_types("contains", (type(self), type(field)))
+ return array_contains_field_operation(self, other, field)
+ return array_contains_operation(self, other)
+
+ def pluck(self, field: StringVar | str) -> ArrayVar:
+ """Pluck a field from the array.
+
+ Args:
+ field: The field to pluck from the array.
+
+ Returns:
+ The array pluck operation.
+ """
+ return array_pluck_operation(self, field)
+
+ @overload
+ def __mul__(self, other: NumberVar | int) -> ArrayVar[ARRAY_VAR_TYPE]: ...
+
+ @overload
+ def __mul__(self, other: NoReturn) -> NoReturn: ...
+
+ def __mul__(self, other: Any) -> ArrayVar[ARRAY_VAR_TYPE]:
+ """Multiply the sequence by a number or integer.
+
+ Parameters:
+ other: The number or integer to multiply the sequence by.
+
+ Returns:
+ ArrayVar[ARRAY_VAR_TYPE]: The result of multiplying the sequence by the given number or integer.
+ """
+ if not isinstance(other, (NumberVar, int)) or (
+ isinstance(other, NumberVar) and other._is_strict_float()
+ ):
+ raise_unsupported_operand_types("*", (type(self), type(other)))
+
+ return repeat_array_operation(self, other)
+
+ __rmul__ = __mul__ # type: ignore
+
+ @overload
+ def __lt__(self, other: ArrayVar[ARRAY_VAR_TYPE]) -> BooleanVar: ...
+
+ @overload
+ def __lt__(self, other: list | tuple) -> BooleanVar: ...
+
+ def __lt__(self, other: Any):
+ """Check if the array is less than another array.
+
+ Args:
+ other: The other array.
+
+ Returns:
+ The array less than operation.
+ """
+ if not isinstance(other, (ArrayVar, list, tuple)):
+ raise_unsupported_operand_types("<", (type(self), type(other)))
+
+ return array_lt_operation(self, other)
+
+ @overload
+ def __gt__(self, other: ArrayVar[ARRAY_VAR_TYPE]) -> BooleanVar: ...
+
+ @overload
+ def __gt__(self, other: list | tuple) -> BooleanVar: ...
+
+ def __gt__(self, other: Any):
+ """Check if the array is greater than another array.
+
+ Args:
+ other: The other array.
+
+ Returns:
+ The array greater than operation.
+ """
+ if not isinstance(other, (ArrayVar, list, tuple)):
+ raise_unsupported_operand_types(">", (type(self), type(other)))
+
+ return array_gt_operation(self, other)
+
+ @overload
+ def __le__(self, other: ArrayVar[ARRAY_VAR_TYPE]) -> BooleanVar: ...
+
+ @overload
+ def __le__(self, other: list | tuple) -> BooleanVar: ...
+
+ def __le__(self, other: Any):
+ """Check if the array is less than or equal to another array.
+
+ Args:
+ other: The other array.
+
+ Returns:
+ The array less than or equal operation.
+ """
+ if not isinstance(other, (ArrayVar, list, tuple)):
+ raise_unsupported_operand_types("<=", (type(self), type(other)))
+
+ return array_le_operation(self, other)
+
+ @overload
+ def __ge__(self, other: ArrayVar[ARRAY_VAR_TYPE]) -> BooleanVar: ...
+
+ @overload
+ def __ge__(self, other: list | tuple) -> BooleanVar: ...
+
+ def __ge__(self, other: Any):
+ """Check if the array is greater than or equal to another array.
+
+ Args:
+ other: The other array.
+
+ Returns:
+ The array greater than or equal operation.
+ """
+ if not isinstance(other, (ArrayVar, list, tuple)):
+ raise_unsupported_operand_types(">=", (type(self), type(other)))
+
+ return array_ge_operation(self, other)
+
+ def foreach(self, fn: Any):
+ """Apply a function to each element of the array.
+
+ Args:
+ fn: The function to apply.
+
+ Returns:
+ The array after applying the function.
+
+ Raises:
+ VarTypeError: If the function takes more than one argument.
+ """
+ from .function import ArgsFunctionOperation
+
+ if not callable(fn):
+ raise_unsupported_operand_types("foreach", (type(self), type(fn)))
+ # get the number of arguments of the function
+ num_args = len(inspect.signature(fn).parameters)
+ if num_args > 1:
+ raise VarTypeError(
+ "The function passed to foreach should take at most one argument."
+ )
+
+ if num_args == 0:
+ return_value = fn()
+ function_var = ArgsFunctionOperation.create(tuple(), return_value)
+ else:
+ # generic number var
+ number_var = Var("").to(NumberVar, int)
+
+ first_arg_type = self[number_var]._var_type
+
+ arg_name = get_unique_variable_name()
+
+ # get first argument type
+ first_arg = Var(
+ _js_expr=arg_name,
+ _var_type=first_arg_type,
+ ).guess_type()
+
+ function_var = ArgsFunctionOperation.create(
+ (arg_name,),
+ Var.create(fn(first_arg)),
+ )
+
+ return map_array_operation(self, function_var)
+
+
+LIST_ELEMENT = TypeVar("LIST_ELEMENT")
+
+ARRAY_VAR_OF_LIST_ELEMENT = Union[
+ ArrayVar[List[LIST_ELEMENT]],
+ ArrayVar[Set[LIST_ELEMENT]],
+ ArrayVar[Tuple[LIST_ELEMENT, ...]],
+]
+
+
+@dataclasses.dataclass(
+ eq=False,
+ frozen=True,
+ **{"slots": True} if sys.version_info >= (3, 10) else {},
+)
+class LiteralArrayVar(CachedVarOperation, LiteralVar, ArrayVar[ARRAY_VAR_TYPE]):
+ """Base class for immutable literal array vars."""
+
+ _var_value: Union[
+ List[Union[Var, Any]],
+ Set[Union[Var, Any]],
+ Tuple[Union[Var, Any], ...],
+ ] = dataclasses.field(default_factory=list)
+
+ @cached_property_no_lock
+ def _cached_var_name(self) -> str:
+ """The name of the var.
+
+ Returns:
+ The name of the var.
+ """
+ return (
+ "["
+ + ", ".join(
+ [str(LiteralVar.create(element)) for element in self._var_value]
+ )
+ + "]"
+ )
+
+ @cached_property_no_lock
+ def _cached_get_all_var_data(self) -> VarData | None:
+ """Get all the VarData associated with the Var.
+
+ Returns:
+ The VarData associated with the Var.
+ """
+ return VarData.merge(
+ *[
+ LiteralVar.create(element)._get_all_var_data()
+ for element in self._var_value
+ ],
+ self._var_data,
+ )
+
+ def __hash__(self) -> int:
+ """Get the hash of the var.
+
+ Returns:
+ The hash of the var.
+ """
+ return hash((self.__class__.__name__, self._js_expr))
+
+ def json(self) -> str:
+ """Get the JSON representation of the var.
+
+ Returns:
+ The JSON representation of the var.
+ """
+ return (
+ "["
+ + ", ".join(
+ [LiteralVar.create(element).json() for element in self._var_value]
+ )
+ + "]"
+ )
+
+ @classmethod
+ def create(
+ cls,
+ value: ARRAY_VAR_TYPE,
+ _var_type: Type[ARRAY_VAR_TYPE] | None = None,
+ _var_data: VarData | None = None,
+ ) -> LiteralArrayVar[ARRAY_VAR_TYPE]:
+ """Create a var from a string value.
+
+ Args:
+ value: The value to create the var from.
+ _var_data: Additional hooks and imports associated with the Var.
+
+ Returns:
+ The var.
+ """
+ return cls(
+ _js_expr="",
+ _var_type=figure_out_type(value) if _var_type is None else _var_type,
+ _var_data=_var_data,
+ _var_value=value,
+ )
+
+
+@var_operation
+def string_split_operation(string: StringVar[Any], sep: StringVar | str = ""):
+ """Split a string.
+
+ Args:
+ string: The string to split.
+ sep: The separator.
+
+ Returns:
+ The split string.
+ """
+ return var_operation_return(
+ js_expression=f"{string}.split({sep})", var_type=List[str]
+ )
+
+
+@dataclasses.dataclass(
+ eq=False,
+ frozen=True,
+ **{"slots": True} if sys.version_info >= (3, 10) else {},
+)
+class ArraySliceOperation(CachedVarOperation, ArrayVar):
+ """Base class for immutable string vars that are the result of a string slice operation."""
+
+ _array: ArrayVar = dataclasses.field(
+ default_factory=lambda: LiteralArrayVar.create([])
+ )
+ _start: NumberVar | int = dataclasses.field(default_factory=lambda: 0)
+ _stop: NumberVar | int = dataclasses.field(default_factory=lambda: 0)
+ _step: NumberVar | int = dataclasses.field(default_factory=lambda: 1)
+
+ @cached_property_no_lock
+ def _cached_var_name(self) -> str:
+ """The name of the var.
+
+ Returns:
+ The name of the var.
+
+ Raises:
+ ValueError: If the slice step is zero.
+ """
+ start, end, step = self._start, self._stop, self._step
+
+ normalized_start = (
+ LiteralVar.create(start) if start is not None else Var(_js_expr="undefined")
+ )
+ normalized_end = (
+ LiteralVar.create(end) if end is not None else Var(_js_expr="undefined")
+ )
+ if step is None:
+ return f"{str(self._array)}.slice({str(normalized_start)}, {str(normalized_end)})"
+ if not isinstance(step, Var):
+ if step < 0:
+ actual_start = end + 1 if end is not None else 0
+ actual_end = start + 1 if start is not None else self._array.length()
+ return str(self._array[actual_start:actual_end].reverse()[::-step])
+ if step == 0:
+ raise ValueError("slice step cannot be zero")
+ return f"{str(self._array)}.slice({str(normalized_start)}, {str(normalized_end)}).filter((_, i) => i % {str(step)} === 0)"
+
+ actual_start_reverse = end + 1 if end is not None else 0
+ actual_end_reverse = start + 1 if start is not None else self._array.length()
+
+ return f"{str(self.step)} > 0 ? {str(self._array)}.slice({str(normalized_start)}, {str(normalized_end)}).filter((_, i) => i % {str(step)} === 0) : {str(self._array)}.slice({str(actual_start_reverse)}, {str(actual_end_reverse)}).reverse().filter((_, i) => i % {str(-step)} === 0)"
+
+ @classmethod
+ def create(
+ cls,
+ array: ArrayVar,
+ slice: slice,
+ _var_data: VarData | None = None,
+ ) -> ArraySliceOperation:
+ """Create a var from a string value.
+
+ Args:
+ array: The array.
+ slice: The slice.
+ _var_data: Additional hooks and imports associated with the Var.
+
+ Returns:
+ The var.
+ """
+ return cls(
+ _js_expr="",
+ _var_type=array._var_type,
+ _var_data=_var_data,
+ _array=array,
+ _start=slice.start,
+ _stop=slice.stop,
+ _step=slice.step,
+ )
+
+
+@var_operation
+def array_pluck_operation(
+ array: ArrayVar[ARRAY_VAR_TYPE],
+ field: StringVar | str,
+) -> CustomVarOperationReturn[ARRAY_VAR_TYPE]:
+ """Pluck a field from an array of objects.
+
+ Args:
+ array: The array to pluck from.
+ field: The field to pluck from the objects in the array.
+
+ Returns:
+ The reversed array.
+ """
+ return var_operation_return(
+ js_expression=f"{array}.map(e=>e?.[{field}])",
+ var_type=array._var_type,
+ )
+
+
+@var_operation
+def array_reverse_operation(
+ array: ArrayVar[ARRAY_VAR_TYPE],
+) -> CustomVarOperationReturn[ARRAY_VAR_TYPE]:
+ """Reverse an array.
+
+ Args:
+ array: The array to reverse.
+
+ Returns:
+ The reversed array.
+ """
+ return var_operation_return(
+ js_expression=f"{array}.slice().reverse()",
+ var_type=array._var_type,
+ )
+
+
+@var_operation
+def array_lt_operation(lhs: ArrayVar | list | tuple, rhs: ArrayVar | list | tuple):
+ """Check if an array is less than another array.
+
+ Args:
+ lhs: The left-hand side array.
+ rhs: The right-hand side array.
+
+ Returns:
+ The array less than operation.
+ """
+ return var_operation_return(js_expression=f"{lhs} < {rhs}", var_type=bool)
+
+
+@var_operation
+def array_gt_operation(lhs: ArrayVar | list | tuple, rhs: ArrayVar | list | tuple):
+ """Check if an array is greater than another array.
+
+ Args:
+ lhs: The left-hand side array.
+ rhs: The right-hand side array.
+
+ Returns:
+ The array greater than operation.
+ """
+ return var_operation_return(js_expression=f"{lhs} > {rhs}", var_type=bool)
+
+
+@var_operation
+def array_le_operation(lhs: ArrayVar | list | tuple, rhs: ArrayVar | list | tuple):
+ """Check if an array is less than or equal to another array.
+
+ Args:
+ lhs: The left-hand side array.
+ rhs: The right-hand side array.
+
+ Returns:
+ The array less than or equal operation.
+ """
+ return var_operation_return(js_expression=f"{lhs} <= {rhs}", var_type=bool)
+
+
+@var_operation
+def array_ge_operation(lhs: ArrayVar | list | tuple, rhs: ArrayVar | list | tuple):
+ """Check if an array is greater than or equal to another array.
+
+ Args:
+ lhs: The left-hand side array.
+ rhs: The right-hand side array.
+
+ Returns:
+ The array greater than or equal operation.
+ """
+ return var_operation_return(js_expression=f"{lhs} >= {rhs}", var_type=bool)
+
+
+@var_operation
+def array_length_operation(array: ArrayVar):
+ """Get the length of an array.
+
+ Args:
+ array: The array.
+
+ Returns:
+ The length of the array.
+ """
+ return var_operation_return(
+ js_expression=f"{array}.length",
+ var_type=int,
+ )
+
+
+def is_tuple_type(t: GenericType) -> bool:
+ """Check if a type is a tuple type.
+
+ Args:
+ t: The type to check.
+
+ Returns:
+ Whether the type is a tuple type.
+ """
+ if inspect.isclass(t):
+ return issubclass(t, tuple)
+ return get_origin(t) is tuple
+
+
+@var_operation
+def array_item_operation(array: ArrayVar, index: NumberVar | int):
+ """Get an item from an array.
+
+ Args:
+ array: The array.
+ index: The index of the item.
+
+ Returns:
+ The item from the array.
+ """
+ args = typing.get_args(array._var_type)
+ if args and isinstance(index, LiteralNumberVar) and is_tuple_type(array._var_type):
+ index_value = int(index._var_value)
+ element_type = args[index_value % len(args)]
+ else:
+ element_type = unionize(*args)
+
+ return var_operation_return(
+ js_expression=f"{str(array)}.at({str(index)})",
+ var_type=element_type,
+ )
+
+
+@var_operation
+def array_range_operation(
+ start: NumberVar | int, stop: NumberVar | int, step: NumberVar | int
+):
+ """Create a range of numbers.
+
+ Args:
+ start: The start of the range.
+ stop: The end of the range.
+ step: The step of the range.
+
+ Returns:
+ The range of numbers.
+ """
+ return var_operation_return(
+ js_expression=f"Array.from({{ length: ({str(stop)} - {str(start)}) / {str(step)} }}, (_, i) => {str(start)} + i * {str(step)})",
+ var_type=List[int],
+ )
+
+
+@var_operation
+def array_contains_field_operation(
+ haystack: ArrayVar, needle: Any | Var, field: StringVar | str
+):
+ """Check if an array contains an element.
+
+ Args:
+ haystack: The array to check.
+ needle: The element to check for.
+ field: The field to check.
+
+ Returns:
+ The array contains operation.
+ """
+ return var_operation_return(
+ js_expression=f"{haystack}.some(obj => obj[{field}] === {needle})",
+ var_type=bool,
+ )
+
+
+@var_operation
+def array_contains_operation(haystack: ArrayVar, needle: Any | Var):
+ """Check if an array contains an element.
+
+ Args:
+ haystack: The array to check.
+ needle: The element to check for.
+
+ Returns:
+ The array contains operation.
+ """
+ return var_operation_return(
+ js_expression=f"{haystack}.includes({needle})",
+ var_type=bool,
+ )
+
+
+@var_operation
+def repeat_array_operation(
+ array: ArrayVar[ARRAY_VAR_TYPE], count: NumberVar | int
+) -> CustomVarOperationReturn[ARRAY_VAR_TYPE]:
+ """Repeat an array a number of times.
+
+ Args:
+ array: The array to repeat.
+ count: The number of times to repeat the array.
+
+ Returns:
+ The repeated array.
+ """
+ return var_operation_return(
+ js_expression=f"Array.from({{ length: {count} }}).flatMap(() => {array})",
+ var_type=array._var_type,
+ )
+
+
+if TYPE_CHECKING:
+ from .function import FunctionVar
+
+
+@var_operation
+def map_array_operation(
+ array: ArrayVar[ARRAY_VAR_TYPE],
+ function: FunctionVar,
+):
+ """Map a function over an array.
+
+ Args:
+ array: The array.
+ function: The function to map.
+
+ Returns:
+ The mapped array.
+ """
+ return var_operation_return(
+ js_expression=f"{array}.map({function})", var_type=List[Any]
+ )
+
+
+@var_operation
+def array_concat_operation(
+ lhs: ArrayVar[ARRAY_VAR_TYPE], rhs: ArrayVar[ARRAY_VAR_TYPE]
+) -> CustomVarOperationReturn[ARRAY_VAR_TYPE]:
+ """Concatenate two arrays.
+
+ Args:
+ lhs: The left-hand side array.
+ rhs: The right-hand side array.
+
+ Returns:
+ The concatenated array.
+ """
+ return var_operation_return(
+ js_expression=f"[...{lhs}, ...{rhs}]",
+ var_type=Union[lhs._var_type, rhs._var_type],
+ )
+
+
+class ColorVar(StringVar[Color], python_types=Color):
+ """Base class for immutable color vars."""
+
+
+@dataclasses.dataclass(
+ eq=False,
+ frozen=True,
+ **{"slots": True} if sys.version_info >= (3, 10) else {},
+)
+class LiteralColorVar(CachedVarOperation, LiteralVar, ColorVar):
+ """Base class for immutable literal color vars."""
+
+ _var_value: Color = dataclasses.field(default_factory=lambda: Color(color="black"))
+
+ @classmethod
+ def create(
+ cls,
+ value: Color,
+ _var_type: Type[Color] | None = None,
+ _var_data: VarData | None = None,
+ ) -> ColorVar:
+ """Create a var from a string value.
+
+ Args:
+ value: The value to create the var from.
+ _var_type: The type of the var.
+ _var_data: Additional hooks and imports associated with the Var.
+
+ Returns:
+ The var.
+ """
+ return cls(
+ _js_expr="",
+ _var_type=_var_type or Color,
+ _var_data=_var_data,
+ _var_value=value,
+ )
+
+ def __hash__(self) -> int:
+ """Get the hash of the var.
+
+ Returns:
+ The hash of the var.
+ """
+ return hash(
+ (
+ self.__class__.__name__,
+ self._var_value.color,
+ self._var_value.alpha,
+ self._var_value.shade,
+ )
+ )
+
+ @cached_property_no_lock
+ def _cached_var_name(self) -> str:
+ """The name of the var.
+
+ Returns:
+ The name of the var.
+ """
+ alpha = self._var_value.alpha
+ alpha = (
+ ternary_operation(
+ alpha,
+ LiteralStringVar.create("a"),
+ LiteralStringVar.create(""),
+ )
+ if isinstance(alpha, Var)
+ else LiteralStringVar.create("a" if alpha else "")
+ )
+
+ shade = self._var_value.shade
+ shade = (
+ shade.to_string(use_json=False)
+ if isinstance(shade, Var)
+ else LiteralStringVar.create(str(shade))
+ )
+ return str(
+ ConcatVarOperation.create(
+ LiteralStringVar.create("var(--"),
+ self._var_value.color,
+ LiteralStringVar.create("-"),
+ alpha,
+ shade,
+ LiteralStringVar.create(")"),
+ )
+ )
+
+ @cached_property_no_lock
+ def _cached_get_all_var_data(self) -> VarData | None:
+ """Get all the var data.
+
+ Returns:
+ The var data.
+ """
+ return VarData.merge(
+ *[
+ LiteralVar.create(var)._get_all_var_data()
+ for var in (
+ self._var_value.color,
+ self._var_value.alpha,
+ self._var_value.shade,
+ )
+ ],
+ self._var_data,
+ )
+
+ def json(self) -> str:
+ """Get the JSON representation of the var.
+
+ Returns:
+ The JSON representation of the var.
+
+ Raises:
+ TypeError: If the color is not a valid color.
+ """
+ color, alpha, shade = map(
+ get_python_literal,
+ (self._var_value.color, self._var_value.alpha, self._var_value.shade),
+ )
+ if color is None or alpha is None or shade is None:
+ raise TypeError("Cannot serialize color that contains non-literal vars.")
+ if (
+ not isinstance(color, str)
+ or not isinstance(alpha, bool)
+ or not isinstance(shade, int)
+ ):
+ raise TypeError("Color is not a valid color.")
+ return f"var(--{color}-{'a' if alpha else ''}{shade})"
diff --git a/scripts/benchmarks/benchmark_reflex_size.py b/scripts/benchmarks/benchmark_reflex_size.py
deleted file mode 100644
index 1bb5e535d..000000000
--- a/scripts/benchmarks/benchmark_reflex_size.py
+++ /dev/null
@@ -1,206 +0,0 @@
-"""Checks the size of a specific directory and uploads result."""
-import argparse
-import os
-import subprocess
-from datetime import datetime
-
-import psycopg2
-
-
-def get_directory_size(directory):
- """Get the size of a directory in bytes.
-
- Args:
- directory: The directory to check.
-
- Returns:
- The size of the dir in bytes.
- """
- total_size = 0
- for dirpath, _, filenames in os.walk(directory):
- for f in filenames:
- fp = os.path.join(dirpath, f)
- total_size += os.path.getsize(fp)
- return total_size
-
-
-def get_python_version(venv_path, os_name):
- """Get the python version of python in a virtual env.
-
- Args:
- venv_path: Path to virtual environment.
- os_name: Name of os.
-
- Returns:
- The python version.
- """
- python_executable = (
- os.path.join(venv_path, "bin", "python")
- if "windows" not in os_name
- else os.path.join(venv_path, "Scripts", "python.exe")
- )
- try:
- output = subprocess.check_output(
- [python_executable, "--version"], stderr=subprocess.STDOUT
- )
- python_version = output.decode("utf-8").strip().split()[1]
- return ".".join(python_version.split(".")[:-1])
- except subprocess.CalledProcessError:
- return None
-
-
-def get_package_size(venv_path, os_name):
- """Get the size of a specified package.
-
- Args:
- venv_path: The path to the venv.
- os_name: Name of os.
-
- Returns:
- The total size of the package in bytes.
-
- Raises:
- ValueError: when venv does not exist or python version is None.
- """
- python_version = get_python_version(venv_path, os_name)
- if python_version is None:
- raise ValueError("Error: Failed to determine Python version.")
-
- is_windows = "windows" in os_name
-
- full_path = (
- ["lib", f"python{python_version}", "site-packages"]
- if not is_windows
- else ["Lib", "site-packages"]
- )
-
- package_dir = os.path.join(venv_path, *full_path)
- if not os.path.exists(package_dir):
- raise ValueError(
- "Error: Virtual environment does not exist or is not activated."
- )
-
- total_size = get_directory_size(package_dir)
- return total_size
-
-
-def insert_benchmarking_data(
- db_connection_url: str,
- os_type_version: str,
- python_version: str,
- measurement_type: str,
- commit_sha: str,
- pr_title: str,
- branch_name: str,
- pr_id: str,
- path: str,
-):
- """Insert the benchmarking data into the database.
-
- Args:
- db_connection_url: The URL to connect to the database.
- os_type_version: The OS type and version to insert.
- python_version: The Python version to insert.
- measurement_type: The type of metric to measure.
- commit_sha: The commit SHA to insert.
- pr_title: The PR title to insert.
- branch_name: The name of the branch.
- pr_id: The id of the PR.
- path: The path to the dir or file to check size.
- """
- if measurement_type == "reflex-package":
- size = get_package_size(path, os_type_version)
- else:
- size = get_directory_size(path)
-
- # Get the current timestamp
- current_timestamp = datetime.now()
-
- # Connect to the database and insert the data
- with psycopg2.connect(db_connection_url) as conn, conn.cursor() as cursor:
- insert_query = """
- INSERT INTO size_benchmarks (os, python_version, commit_sha, created_at, pr_title, branch_name, pr_id, measurement_type, size)
- VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s);
- """
- cursor.execute(
- insert_query,
- (
- os_type_version,
- python_version,
- commit_sha,
- current_timestamp,
- pr_title,
- branch_name,
- pr_id,
- measurement_type,
- round(
- size / (1024 * 1024), 3
- ), # save size in mb and round to 3 places.
- ),
- )
- # Commit the transaction
- conn.commit()
-
-
-def main():
- """Runs the benchmarks and inserts the results."""
- parser = argparse.ArgumentParser(description="Run benchmarks and process results.")
- parser.add_argument(
- "--os", help="The OS type and version to insert into the database."
- )
- parser.add_argument(
- "--python-version", help="The Python version to insert into the database."
- )
- parser.add_argument(
- "--commit-sha", help="The commit SHA to insert into the database."
- )
- parser.add_argument(
- "--db-url",
- help="The URL to connect to the database.",
- required=True,
- )
- parser.add_argument(
- "--pr-title",
- help="The PR title to insert into the database.",
- )
- parser.add_argument(
- "--branch-name",
- help="The current branch",
- required=True,
- )
- parser.add_argument(
- "--pr-id",
- help="The pr id",
- required=True,
- )
- parser.add_argument(
- "--measurement-type",
- help="The type of metric to be checked.",
- required=True,
- )
- parser.add_argument(
- "--path",
- help="the current path to check size.",
- required=True,
- )
- args = parser.parse_args()
-
- # Get the PR title from env or the args. For the PR merge or push event, there is no PR title, leaving it empty.
- pr_title = args.pr_title or os.getenv("PR_TITLE", "")
-
- # Insert the data into the database
- insert_benchmarking_data(
- db_connection_url=args.db_url,
- os_type_version=args.os,
- python_version=args.python_version,
- measurement_type=args.measurement_type,
- commit_sha=args.commit_sha,
- pr_title=pr_title,
- branch_name=args.branch_name,
- pr_id=args.pr_id,
- path=args.path,
- )
-
-
-if __name__ == "__main__":
- main()
diff --git a/scripts/benchmarks/lighthouse_score_upload.py b/scripts/benchmarks/lighthouse_score_upload.py
deleted file mode 100644
index 35f32f5d9..000000000
--- a/scripts/benchmarks/lighthouse_score_upload.py
+++ /dev/null
@@ -1,109 +0,0 @@
-"""Runs the benchmarks and inserts the results into the database."""
-
-from __future__ import annotations
-
-import json
-import os
-import sys
-from datetime import datetime
-
-import psycopg2
-
-
-def insert_benchmarking_data(
- db_connection_url: str,
- lighthouse_data: dict,
- commit_sha: str,
- pr_title: str,
-):
- """Insert the benchmarking data into the database.
-
- Args:
- db_connection_url: The URL to connect to the database.
- lighthouse_data: The Lighthouse data to insert.
- commit_sha: The commit SHA to insert.
- pr_title: The PR title to insert.
- """
- # Serialize the JSON data
- lighthouse_json = json.dumps(lighthouse_data)
-
- # Get the current timestamp
- current_timestamp = datetime.now()
-
- # Connect to the database and insert the data
- with psycopg2.connect(db_connection_url) as conn, conn.cursor() as cursor:
- insert_query = """
- INSERT INTO benchmarks (lighthouse, commit_sha, pr_title, time)
- VALUES (%s, %s, %s, %s);
- """
- cursor.execute(
- insert_query,
- (
- lighthouse_json,
- commit_sha,
- pr_title,
- current_timestamp,
- ),
- )
- # Commit the transaction
- conn.commit()
-
-
-def get_lighthouse_scores(directory_path: str) -> dict:
- """Extracts the Lighthouse scores from the JSON files in the specified directory.
-
- Args:
- directory_path (str): The path to the directory containing the JSON files.
-
- Returns:
- dict: The Lighthouse scores.
- """
- scores = {}
-
- try:
- for filename in os.listdir(directory_path):
- if filename.endswith(".json") and filename != "manifest.json":
- file_path = os.path.join(directory_path, filename)
- with open(file_path, "r") as file:
- data = json.load(file)
- # Extract scores and add them to the dictionary with the filename as key
- scores[data["finalUrl"].replace("http://localhost:3000/", "")] = {
- "performance_score": data["categories"]["performance"]["score"],
- "accessibility_score": data["categories"]["accessibility"][
- "score"
- ],
- "best_practices_score": data["categories"]["best-practices"][
- "score"
- ],
- "seo_score": data["categories"]["seo"]["score"],
- "pwa_score": data["categories"]["pwa"]["score"],
- }
- except Exception as e:
- print(e)
- return {"error": "Error parsing JSON files"}
-
- return scores
-
-
-def main():
- """Runs the benchmarks and inserts the results into the database."""
- # Get the commit SHA and JSON directory from the command line arguments
- commit_sha = sys.argv[1]
- json_dir = sys.argv[2]
-
- # Get the PR title and database URL from the environment variables
- pr_title = os.environ.get("PR_TITLE")
- db_url = os.environ.get("DATABASE_URL")
-
- if db_url is None or pr_title is None:
- sys.exit("Missing environment variables")
-
- # Get the Lighthouse scores
- lighthouse_scores = get_lighthouse_scores(json_dir)
-
- # Insert the data into the database
- insert_benchmarking_data(db_url, lighthouse_scores, commit_sha, pr_title)
-
-
-if __name__ == "__main__":
- main()
diff --git a/scripts/bun_install.sh b/scripts/bun_install.sh
new file mode 100644
index 000000000..08a0817f6
--- /dev/null
+++ b/scripts/bun_install.sh
@@ -0,0 +1,311 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+platform=$(uname -ms)
+
+if [[ ${OS:-} = Windows_NT ]]; then
+ if [[ $platform != MINGW64* ]]; then
+ powershell -c "irm bun.sh/install.ps1|iex"
+ exit $?
+ fi
+fi
+
+# Reset
+Color_Off=''
+
+# Regular Colors
+Red=''
+Green=''
+Dim='' # White
+
+# Bold
+Bold_White=''
+Bold_Green=''
+
+if [[ -t 1 ]]; then
+ # Reset
+ Color_Off='\033[0m' # Text Reset
+
+ # Regular Colors
+ Red='\033[0;31m' # Red
+ Green='\033[0;32m' # Green
+ Dim='\033[0;2m' # White
+
+ # Bold
+ Bold_Green='\033[1;32m' # Bold Green
+ Bold_White='\033[1m' # Bold White
+fi
+
+error() {
+ echo -e "${Red}error${Color_Off}:" "$@" >&2
+ exit 1
+}
+
+info() {
+ echo -e "${Dim}$@ ${Color_Off}"
+}
+
+info_bold() {
+ echo -e "${Bold_White}$@ ${Color_Off}"
+}
+
+success() {
+ echo -e "${Green}$@ ${Color_Off}"
+}
+
+command -v unzip >/dev/null ||
+ error 'unzip is required to install bun'
+
+if [[ $# -gt 2 ]]; then
+ error 'Too many arguments, only 2 are allowed. The first can be a specific tag of bun to install. (e.g. "bun-v0.1.4") The second can be a build variant of bun to install. (e.g. "debug-info")'
+fi
+
+case $platform in
+'Darwin x86_64')
+ target=darwin-x64
+ ;;
+'Darwin arm64')
+ target=darwin-aarch64
+ ;;
+'Linux aarch64' | 'Linux arm64')
+ target=linux-aarch64
+ ;;
+'MINGW64'*)
+ target=windows-x64
+ ;;
+'Linux x86_64' | *)
+ target=linux-x64
+ ;;
+esac
+
+if [[ $target = darwin-x64 ]]; then
+ # Is this process running in Rosetta?
+ # redirect stderr to devnull to avoid error message when not running in Rosetta
+ if [[ $(sysctl -n sysctl.proc_translated 2>/dev/null) = 1 ]]; then
+ target=darwin-aarch64
+ info "Your shell is running in Rosetta 2. Downloading bun for $target instead"
+ fi
+fi
+
+GITHUB=${GITHUB-"https://github.com"}
+
+github_repo="$GITHUB/oven-sh/bun"
+
+if [[ $target = darwin-x64 ]]; then
+ # If AVX2 isn't supported, use the -baseline build
+ if [[ $(sysctl -a | grep machdep.cpu | grep AVX2) == '' ]]; then
+ target=darwin-x64-baseline
+ fi
+fi
+
+if [[ $target = linux-x64 ]]; then
+ # If AVX2 isn't supported, use the -baseline build
+ if [[ $(cat /proc/cpuinfo | grep avx2) = '' ]]; then
+ target=linux-x64-baseline
+ fi
+fi
+
+exe_name=bun
+
+if [[ $# = 2 && $2 = debug-info ]]; then
+ target=$target-profile
+ exe_name=bun-profile
+ info "You requested a debug build of bun. More information will be shown if a crash occurs."
+fi
+
+if [[ $# = 0 ]]; then
+ bun_uri=$github_repo/releases/latest/download/bun-$target.zip
+else
+ bun_uri=$github_repo/releases/download/$1/bun-$target.zip
+fi
+
+install_env=BUN_INSTALL
+bin_env=\$$install_env/bin
+
+install_dir=${!install_env:-$HOME/.bun}
+bin_dir=$install_dir/bin
+exe=$bin_dir/bun
+
+if [[ ! -d $bin_dir ]]; then
+ mkdir -p "$bin_dir" ||
+ error "Failed to create install directory \"$bin_dir\""
+fi
+
+curl --fail --location --progress-bar --output "$exe.zip" "$bun_uri" ||
+ error "Failed to download bun from \"$bun_uri\""
+
+unzip -oqd "$bin_dir" "$exe.zip" ||
+ error 'Failed to extract bun'
+
+mv "$bin_dir/bun-$target/$exe_name" "$exe" ||
+ error 'Failed to move extracted bun to destination'
+
+chmod +x "$exe" ||
+ error 'Failed to set permissions on bun executable'
+
+rm -r "$bin_dir/bun-$target" "$exe.zip"
+
+tildify() {
+ if [[ $1 = $HOME/* ]]; then
+ local replacement=\~/
+
+ echo "${1/$HOME\//$replacement}"
+ else
+ echo "$1"
+ fi
+}
+
+success "bun was installed successfully to $Bold_Green$(tildify "$exe")"
+
+if command -v bun >/dev/null; then
+ # Install completions, but we don't care if it fails
+ IS_BUN_AUTO_UPDATE=true $exe completions &>/dev/null || :
+
+ echo "Run 'bun --help' to get started"
+ exit
+fi
+
+refresh_command=''
+
+tilde_bin_dir=$(tildify "$bin_dir")
+quoted_install_dir=\"${install_dir//\"/\\\"}\"
+
+if [[ $quoted_install_dir = \"$HOME/* ]]; then
+ quoted_install_dir=${quoted_install_dir/$HOME\//\$HOME/}
+fi
+
+echo
+
+case $(basename "$SHELL") in
+fish)
+ # Install completions, but we don't care if it fails
+ IS_BUN_AUTO_UPDATE=true SHELL=fish $exe completions &>/dev/null || :
+
+ commands=(
+ "set --export $install_env $quoted_install_dir"
+ "set --export PATH $bin_env \$PATH"
+ )
+
+ fish_config=$HOME/.config/fish/config.fish
+ tilde_fish_config=$(tildify "$fish_config")
+
+ if [[ -w $fish_config ]]; then
+ {
+ echo -e '\n# bun'
+
+ for command in "${commands[@]}"; do
+ echo "$command"
+ done
+ } >>"$fish_config"
+
+ info "Added \"$tilde_bin_dir\" to \$PATH in \"$tilde_fish_config\""
+
+ refresh_command="source $tilde_fish_config"
+ else
+ echo "Manually add the directory to $tilde_fish_config (or similar):"
+
+ for command in "${commands[@]}"; do
+ info_bold " $command"
+ done
+ fi
+ ;;
+zsh)
+ # Install completions, but we don't care if it fails
+ IS_BUN_AUTO_UPDATE=true SHELL=zsh $exe completions &>/dev/null || :
+
+ commands=(
+ "export $install_env=$quoted_install_dir"
+ "export PATH=\"$bin_env:\$PATH\""
+ )
+
+ zsh_config=$HOME/.zshrc
+ tilde_zsh_config=$(tildify "$zsh_config")
+
+ if [[ -w $zsh_config ]]; then
+ {
+ echo -e '\n# bun'
+
+ for command in "${commands[@]}"; do
+ echo "$command"
+ done
+ } >>"$zsh_config"
+
+ info "Added \"$tilde_bin_dir\" to \$PATH in \"$tilde_zsh_config\""
+
+ refresh_command="exec $SHELL"
+ else
+ echo "Manually add the directory to $tilde_zsh_config (or similar):"
+
+ for command in "${commands[@]}"; do
+ info_bold " $command"
+ done
+ fi
+ ;;
+bash)
+ # Install completions, but we don't care if it fails
+ IS_BUN_AUTO_UPDATE=true SHELL=bash $exe completions &>/dev/null || :
+
+ commands=(
+ "export $install_env=$quoted_install_dir"
+ "export PATH=\"$bin_env:\$PATH\""
+ )
+
+ bash_configs=(
+ "$HOME/.bashrc"
+ "$HOME/.bash_profile"
+ )
+
+ if [[ ${XDG_CONFIG_HOME:-} ]]; then
+ bash_configs+=(
+ "$XDG_CONFIG_HOME/.bash_profile"
+ "$XDG_CONFIG_HOME/.bashrc"
+ "$XDG_CONFIG_HOME/bash_profile"
+ "$XDG_CONFIG_HOME/bashrc"
+ )
+ fi
+
+ set_manually=true
+ for bash_config in "${bash_configs[@]}"; do
+ tilde_bash_config=$(tildify "$bash_config")
+
+ if [[ -w $bash_config ]]; then
+ {
+ echo -e '\n# bun'
+
+ for command in "${commands[@]}"; do
+ echo "$command"
+ done
+ } >>"$bash_config"
+
+ info "Added \"$tilde_bin_dir\" to \$PATH in \"$tilde_bash_config\""
+
+ refresh_command="source $bash_config"
+ set_manually=false
+ break
+ fi
+ done
+
+ if [[ $set_manually = true ]]; then
+ echo "Manually add the directory to $tilde_bash_config (or similar):"
+
+ for command in "${commands[@]}"; do
+ info_bold " $command"
+ done
+ fi
+ ;;
+*)
+ echo 'Manually add the directory to ~/.bashrc (or similar):'
+ info_bold " export $install_env=$quoted_install_dir"
+ info_bold " export PATH=\"$bin_env:\$PATH\""
+ ;;
+esac
+
+echo
+info "To get started, run:"
+echo
+
+if [[ $refresh_command ]]; then
+ info_bold " $refresh_command"
+fi
+
+info_bold " bun --help"
diff --git a/scripts/make_pyi.py b/scripts/make_pyi.py
index 10a2e1acd..c17200b8a 100644
--- a/scripts/make_pyi.py
+++ b/scripts/make_pyi.py
@@ -5,13 +5,14 @@ import subprocess
import sys
from pathlib import Path
-from reflex.utils.pyi_generator import PyiGenerator, _relative_to_pwd, generate_init
+from reflex.utils.pyi_generator import PyiGenerator, _relative_to_pwd
logger = logging.getLogger("pyi_generator")
LAST_RUN_COMMIT_SHA_FILE = Path(".pyi_generator_last_run").resolve()
GENERATOR_FILE = Path(__file__).resolve()
GENERATOR_DIFF_FILE = Path(".pyi_generator_diff").resolve()
+DEFAULT_TARGETS = ["reflex/components", "reflex/experimental", "reflex/__init__.py"]
def _git_diff(args: list[str]) -> str:
@@ -92,8 +93,16 @@ if __name__ == "__main__":
targets = (
[arg for arg in sys.argv[1:] if not arg.startswith("tests")]
if len(sys.argv) > 1
- else ["reflex/components"]
+ else DEFAULT_TARGETS
)
+
+ # Only include targets that have a prefix in the default target list
+ targets = [
+ target
+ for target in targets
+ if any(str(target).startswith(prefix) for prefix in DEFAULT_TARGETS)
+ ]
+
logger.info(f"Running .pyi generator for {targets}")
changed_files = _get_changed_files()
@@ -104,7 +113,6 @@ if __name__ == "__main__":
gen = PyiGenerator()
gen.scan_all(targets, changed_files)
- generate_init()
current_commit_sha = subprocess.run(
["git", "rev-parse", "HEAD"], capture_output=True, encoding="utf-8"
diff --git a/scripts/migrate_project_to_rx_chakra.py b/scripts/migrate_project_to_rx_chakra.py
deleted file mode 100644
index b13cccafd..000000000
--- a/scripts/migrate_project_to_rx_chakra.py
+++ /dev/null
@@ -1,13 +0,0 @@
-"""Migrate project to rx.chakra. I.e. switch usage of rx. to rx.chakra.."""
-
-import argparse
-
-if __name__ == "__main__":
- # parse args just for the help message (-h, etc)
- parser = argparse.ArgumentParser(
- description="Migrate project to rx.chakra. I.e. switch usage of rx. to rx.chakra.."
- )
- args = parser.parse_args()
- from reflex.utils.prerequisites import migrate_to_rx_chakra
-
- migrate_to_rx_chakra()
diff --git a/scripts/wait_for_listening_port.py b/scripts/wait_for_listening_port.py
index 093b8e7e2..247ff4fba 100644
--- a/scripts/wait_for_listening_port.py
+++ b/scripts/wait_for_listening_port.py
@@ -3,6 +3,7 @@
Replaces logic previously implemented in a shell script that needed
tools that are not available on Windows.
"""
+
import argparse
import socket
import time
diff --git a/tests/__init__.py b/tests/__init__.py
index b4d8570e5..d0196603c 100644
--- a/tests/__init__.py
+++ b/tests/__init__.py
@@ -1,4 +1,5 @@
"""Root directory for tests."""
+
import os
from reflex import constants
diff --git a/tests/components/core/test_colors.py b/tests/components/core/test_colors.py
deleted file mode 100644
index 53aa4d86c..000000000
--- a/tests/components/core/test_colors.py
+++ /dev/null
@@ -1,116 +0,0 @@
-import pytest
-
-import reflex as rx
-from reflex.components.datadisplay.code import CodeBlock
-from reflex.vars import Var
-
-
-class ColorState(rx.State):
- """Test color state."""
-
- color: str = "mint"
- color_part: str = "tom"
- shade: int = 4
-
-
-def create_color_var(color):
- return Var.create(color)
-
-
-@pytest.mark.parametrize(
- "color, expected",
- [
- (create_color_var(rx.color("mint")), "var(--mint-7)"),
- (create_color_var(rx.color("mint", 3)), "var(--mint-3)"),
- (create_color_var(rx.color("mint", 3, True)), "var(--mint-a3)"),
- (
- create_color_var(rx.color(ColorState.color, ColorState.shade)), # type: ignore
- "var(--${state__color_state.color}-${state__color_state.shade})",
- ),
- (
- create_color_var(rx.color(f"{ColorState.color}", f"{ColorState.shade}")), # type: ignore
- "var(--${state__color_state.color}-${state__color_state.shade})",
- ),
- (
- create_color_var(
- rx.color(f"{ColorState.color_part}ato", f"{ColorState.shade}") # type: ignore
- ),
- "var(--${state__color_state.color_part}ato-${state__color_state.shade})",
- ),
- (
- create_color_var(f'{rx.color(ColorState.color, f"{ColorState.shade}")}'), # type: ignore
- "var(--${state__color_state.color}-${state__color_state.shade})",
- ),
- (
- create_color_var(
- f'{rx.color(f"{ColorState.color}", f"{ColorState.shade}")}' # type: ignore
- ),
- "var(--${state__color_state.color}-${state__color_state.shade})",
- ),
- ],
-)
-def test_color(color, expected):
- assert str(color) == expected
-
-
-@pytest.mark.parametrize(
- "cond_var, expected",
- [
- (
- rx.cond(True, rx.color("mint"), rx.color("tomato", 5)),
- "{isTrue(true) ? `var(--mint-7)` : `var(--tomato-5)`}",
- ),
- (
- rx.cond(True, rx.color(ColorState.color), rx.color(ColorState.color, 5)), # type: ignore
- "{isTrue(true) ? `var(--${state__color_state.color}-7)` : `var(--${state__color_state.color}-5)`}",
- ),
- (
- rx.match(
- "condition",
- ("first", rx.color("mint")),
- ("second", rx.color("tomato", 5)),
- rx.color(ColorState.color, 2), # type: ignore
- ),
- "{(() => { switch (JSON.stringify(`condition`)) {case JSON.stringify(`first`): return (`var(--mint-7)`);"
- " break;case JSON.stringify(`second`): return (`var(--tomato-5)`); break;default: "
- "return (`var(--${state__color_state.color}-2)`); break;};})()}",
- ),
- (
- rx.match(
- "condition",
- ("first", rx.color(ColorState.color)), # type: ignore
- ("second", rx.color(ColorState.color, 5)), # type: ignore
- rx.color(ColorState.color, 2), # type: ignore
- ),
- "{(() => { switch (JSON.stringify(`condition`)) {case JSON.stringify(`first`): "
- "return (`var(--${state__color_state.color}-7)`); break;case JSON.stringify(`second`): "
- "return (`var(--${state__color_state.color}-5)`); break;default: "
- "return (`var(--${state__color_state.color}-2)`); break;};})()}",
- ),
- ],
-)
-def test_color_with_conditionals(cond_var, expected):
- assert str(cond_var) == expected
-
-
-@pytest.mark.parametrize(
- "color, expected",
- [
- (create_color_var(rx.color("red")), "var(--red-7)"),
- (create_color_var(rx.color("green", shade=1)), "var(--green-1)"),
- (create_color_var(rx.color("blue", alpha=True)), "var(--blue-a7)"),
- ("red", "red"),
- ("green", "green"),
- ("blue", "blue"),
- ],
-)
-def test_radix_color(color, expected):
- """Test that custom_style can accept both string
- literals and rx.color inputs.
-
- Args:
- color (Color): A Color made with rx.color
- expected (str): The expected custom_style string, radix or literal
- """
- code_block = CodeBlock.create("Hello World", background_color=color)
- assert code_block.custom_style["backgroundColor"].__format__("") == expected # type: ignore
diff --git a/tests/components/core/test_html.py b/tests/components/core/test_html.py
deleted file mode 100644
index 325bdcaf9..000000000
--- a/tests/components/core/test_html.py
+++ /dev/null
@@ -1,22 +0,0 @@
-import pytest
-
-from reflex.components.core.html import Html
-
-
-def test_html_no_children():
- with pytest.raises(ValueError):
- _ = Html.create()
-
-
-def test_html_many_children():
- with pytest.raises(ValueError):
- _ = Html.create("foo", "bar")
-
-
-def test_html_create():
- html = Html.create("Hello !
")
- assert str(html.dangerouslySetInnerHTML) == '{"__html": "Hello !
"}' # type: ignore
- assert (
- str(html)
- == 'Hello !"}}/>'
- )
diff --git a/tests/components/datadisplay/test_table.py b/tests/components/datadisplay/test_table.py
deleted file mode 100644
index 1cec624e9..000000000
--- a/tests/components/datadisplay/test_table.py
+++ /dev/null
@@ -1,177 +0,0 @@
-import sys
-from typing import List, Tuple
-
-import pytest
-
-from reflex.components.chakra.datadisplay.table import Tbody, Tfoot, Thead
-from reflex.state import BaseState
-
-PYTHON_GT_V38 = sys.version_info.major >= 3 and sys.version_info.minor > 8
-
-
-class TableState(BaseState):
- """Test State class."""
-
- rows_List_List_str: List[List[str]] = [["random", "row"]]
- rows_List_List: List[List] = [["random", "row"]]
- rows_List_str: List[str] = ["random", "row"]
- rows_Tuple_List_str: Tuple[List[str]] = (["random", "row"],)
- rows_Tuple_List: Tuple[List] = ["random", "row"] # type: ignore
- rows_Tuple_str_str: Tuple[str, str] = (
- "random",
- "row",
- )
- rows_Tuple_Tuple_str_str: Tuple[Tuple[str, str]] = (
- (
- "random",
- "row",
- ),
- )
- rows_Tuple_Tuple: Tuple[Tuple] = (
- (
- "random",
- "row",
- ),
- )
- rows_str: str = "random, row"
- headers_List_str: List[str] = ["header1", "header2"]
- headers_Tuple_str_str: Tuple[str, str] = (
- "header1",
- "header2",
- )
- headers_str: str = "headers1, headers2"
- footers_List_str: List[str] = ["footer1", "footer2"]
- footers_Tuple_str_str: Tuple[str, str] = (
- "footer1",
- "footer2",
- )
- footers_str: str = "footer1, footer2"
-
- if sys.version_info.major >= 3 and sys.version_info.minor > 8:
- rows_list_list_str: list[list[str]] = [["random", "row"]]
- rows_list_list: list[list] = [["random", "row"]]
- rows_list_str: list[str] = ["random", "row"]
- rows_tuple_list_str: tuple[list[str]] = (["random", "row"],)
- rows_tuple_list: tuple[list] = ["random", "row"] # type: ignore
- rows_tuple_str_str: tuple[str, str] = (
- "random",
- "row",
- )
- rows_tuple_tuple_str_str: tuple[tuple[str, str]] = (
- (
- "random",
- "row",
- ),
- )
- rows_tuple_tuple: tuple[tuple] = (
- (
- "random",
- "row",
- ),
- )
-
-
-valid_extras = (
- [
- TableState.rows_list_list_str,
- TableState.rows_list_list,
- TableState.rows_tuple_list_str,
- TableState.rows_tuple_list,
- TableState.rows_tuple_tuple_str_str,
- TableState.rows_tuple_tuple,
- ]
- if PYTHON_GT_V38
- else []
-)
-invalid_extras = (
- [TableState.rows_list_str, TableState.rows_tuple_str_str] if PYTHON_GT_V38 else []
-)
-
-
-@pytest.mark.parametrize(
- "rows",
- [
- [["random", "row"]],
- TableState.rows_List_List_str,
- TableState.rows_List_List,
- TableState.rows_Tuple_List_str,
- TableState.rows_Tuple_List,
- TableState.rows_Tuple_Tuple_str_str,
- TableState.rows_Tuple_Tuple,
- *valid_extras,
- ],
-)
-def test_create_table_body_with_valid_rows_prop(rows):
- render_dict = Tbody.create(rows=rows).render()
- assert render_dict["name"] == "Tbody"
- assert len(render_dict["children"]) == 1
-
-
-@pytest.mark.parametrize(
- "rows",
- [
- ["random", "row"],
- "random, rows",
- TableState.rows_List_str,
- TableState.rows_Tuple_str_str,
- TableState.rows_str,
- *invalid_extras,
- ],
-)
-def test_create_table_body_with_invalid_rows_prop(rows):
- with pytest.raises(TypeError):
- Tbody.create(rows=rows)
-
-
-@pytest.mark.parametrize(
- "headers",
- [
- ["random", "header"],
- TableState.headers_List_str,
- TableState.headers_Tuple_str_str,
- ],
-)
-def test_create_table_head_with_valid_headers_prop(headers):
- render_dict = Thead.create(headers=headers).render()
- assert render_dict["name"] == "Thead"
- assert len(render_dict["children"]) == 1
- assert render_dict["children"][0]["name"] == "Tr"
-
-
-@pytest.mark.parametrize(
- "headers",
- [
- "random, header",
- TableState.headers_str,
- ],
-)
-def test_create_table_head_with_invalid_headers_prop(headers):
- with pytest.raises(TypeError):
- Thead.create(headers=headers)
-
-
-@pytest.mark.parametrize(
- "footers",
- [
- ["random", "footers"],
- TableState.footers_List_str,
- TableState.footers_Tuple_str_str,
- ],
-)
-def test_create_table_footer_with_valid_footers_prop(footers):
- render_dict = Tfoot.create(footers=footers).render()
- assert render_dict["name"] == "Tfoot"
- assert len(render_dict["children"]) == 1
- assert render_dict["children"][0]["name"] == "Tr"
-
-
-@pytest.mark.parametrize(
- "footers",
- [
- "random, footers",
- TableState.footers_str,
- ],
-)
-def test_create_table_footer_with_invalid_footers_prop(footers):
- with pytest.raises(TypeError):
- Tfoot.create(footers=footers)
diff --git a/tests/components/forms/test_uploads.py b/tests/components/forms/test_uploads.py
deleted file mode 100644
index 930d669ef..000000000
--- a/tests/components/forms/test_uploads.py
+++ /dev/null
@@ -1,161 +0,0 @@
-import pytest
-
-import reflex as rx
-
-
-@pytest.fixture
-def upload_root_component():
- """A test upload component function.
-
- Returns:
- A test upload component function.
- """
-
- def upload_root_component():
- return rx.upload.root(
- rx.button("select file"),
- rx.text("Drag and drop files here or click to select files"),
- border="1px dotted black",
- )
-
- return upload_root_component()
-
-
-@pytest.fixture
-def upload_component():
- """A test upload component function.
-
- Returns:
- A test upload component function.
- """
-
- def upload_component():
- return rx.upload(
- rx.button("select file"),
- rx.text("Drag and drop files here or click to select files"),
- border="1px dotted black",
- )
-
- return upload_component()
-
-
-@pytest.fixture
-def upload_component_with_props():
- """A test upload component with props function.
-
- Returns:
- A test upload component with props function.
- """
-
- def upload_component_with_props():
- return rx.upload(
- rx.button("select file"),
- rx.text("Drag and drop files here or click to select files"),
- border="1px dotted black",
- no_drag=True,
- max_files=2,
- )
-
- return upload_component_with_props()
-
-
-def test_upload_root_component_render(upload_root_component):
- """Test that the render function is set correctly.
-
- Args:
- upload_root_component: component fixture
- """
- upload = upload_root_component.render()
-
- # upload
- assert upload["name"] == "ReactDropzone"
- assert upload["props"] == [
- "id={`default`}",
- "multiple={true}",
- "onDrop={e => setFilesById(filesById => ({...filesById, default: e}))}",
- "ref={ref_default}",
- ]
- assert upload["args"] == ("getRootProps", "getInputProps")
-
- # box inside of upload
- [box] = upload["children"]
- assert box["name"] == "Box"
- assert box["props"] == [
- "className={`rx-Upload`}",
- 'sx={{"border": "1px dotted black"}}',
- "{...getRootProps()}",
- ]
-
- # input, button and text inside of box
- [input, button, text] = box["children"]
- assert input["name"] == "Input"
- assert input["props"] == ["type={`file`}", "{...getInputProps()}"]
-
- assert button["name"] == "RadixThemesButton"
- assert button["children"][0]["contents"] == "{`select file`}"
-
- assert text["name"] == "RadixThemesText"
- assert (
- text["children"][0]["contents"]
- == "{`Drag and drop files here or click to select files`}"
- )
-
-
-def test_upload_component_render(upload_component):
- """Test that the render function is set correctly.
-
- Args:
- upload_component: component fixture
- """
- upload = upload_component.render()
-
- # upload
- assert upload["name"] == "ReactDropzone"
- assert upload["props"] == [
- "id={`default`}",
- "multiple={true}",
- "onDrop={e => setFilesById(filesById => ({...filesById, default: e}))}",
- "ref={ref_default}",
- ]
- assert upload["args"] == ("getRootProps", "getInputProps")
-
- # box inside of upload
- [box] = upload["children"]
- assert box["name"] == "Box"
- assert box["props"] == [
- "className={`rx-Upload`}",
- 'sx={{"border": "1px dotted black", "padding": "5em", "textAlign": "center"}}',
- "{...getRootProps()}",
- ]
-
- # input, button and text inside of box
- [input, button, text] = box["children"]
- assert input["name"] == "Input"
- assert input["props"] == ["type={`file`}", "{...getInputProps()}"]
-
- assert button["name"] == "RadixThemesButton"
- assert button["children"][0]["contents"] == "{`select file`}"
-
- assert text["name"] == "RadixThemesText"
- assert (
- text["children"][0]["contents"]
- == "{`Drag and drop files here or click to select files`}"
- )
-
-
-def test_upload_component_with_props_render(upload_component_with_props):
- """Test that the render function is set correctly.
-
- Args:
- upload_component_with_props: component fixture
- """
- upload = upload_component_with_props.render()
-
- assert upload["props"] == [
- "id={`default`}",
- "maxFiles={2}",
- "multiple={true}",
- "noDrag={true}",
- "onDrop={e => setFilesById(filesById => ({...filesById, default: e}))}",
- "ref={ref_default}",
- ]
diff --git a/tests/components/media/test_icon.py b/tests/components/media/test_icon.py
deleted file mode 100644
index 95dc8de28..000000000
--- a/tests/components/media/test_icon.py
+++ /dev/null
@@ -1,55 +0,0 @@
-import pytest
-
-from reflex.components.chakra.media.icon import ICON_LIST, Icon
-from reflex.utils import format
-
-
-def test_no_tag_errors():
- """Test that an icon without a tag raises an error."""
- with pytest.raises(AttributeError):
- Icon.create()
-
-
-def test_children_errors():
- """Test that an icon with children raises an error."""
- with pytest.raises(AttributeError):
- Icon.create("child", tag="search")
-
-
-@pytest.mark.parametrize(
- "tag",
- ICON_LIST,
-)
-def test_valid_icon(tag: str):
- """Test that a valid icon does not raise an error.
-
- Args:
- tag: The icon tag.
- """
- icon = Icon.create(tag=tag)
- assert icon.tag == format.to_title_case(tag) + "Icon"
-
-
-@pytest.mark.parametrize("tag", ["", " ", "invalid", 123])
-def test_invalid_icon(tag):
- """Test that an invalid icon raises an error.
-
- Args:
- tag: The icon tag.
- """
- with pytest.raises(ValueError):
- Icon.create(tag=tag)
-
-
-@pytest.mark.parametrize(
- "tag",
- ["Check", "Close", "eDit"],
-)
-def test_tag_with_capital(tag: str):
- """Test that an icon that tag with capital does not raise an error.
-
- Args:
- tag: The icon tag.
- """
- icon = Icon.create(tag=tag)
- assert icon.tag == format.to_title_case(tag) + "Icon"
diff --git a/integration/__init__.py b/tests/integration/__init__.py
similarity index 100%
rename from integration/__init__.py
rename to tests/integration/__init__.py
diff --git a/integration/conftest.py b/tests/integration/conftest.py
similarity index 100%
rename from integration/conftest.py
rename to tests/integration/conftest.py
diff --git a/integration/init-test/Dockerfile b/tests/integration/init-test/Dockerfile
similarity index 91%
rename from integration/init-test/Dockerfile
rename to tests/integration/init-test/Dockerfile
index aa11344b1..f30466e7f 100644
--- a/integration/init-test/Dockerfile
+++ b/tests/integration/init-test/Dockerfile
@@ -1,4 +1,4 @@
-FROM python:3.8
+FROM python:3.9
ARG USERNAME=kerrigan
RUN useradd -m $USERNAME
diff --git a/integration/init-test/in_docker_test_script.sh b/tests/integration/init-test/in_docker_test_script.sh
similarity index 96%
rename from integration/init-test/in_docker_test_script.sh
rename to tests/integration/init-test/in_docker_test_script.sh
index 4e898ac99..31d245588 100755
--- a/integration/init-test/in_docker_test_script.sh
+++ b/tests/integration/init-test/in_docker_test_script.sh
@@ -13,7 +13,7 @@ function do_export () {
reflex init --template "$template"
reflex export
(
- cd "$SCRIPTPATH/../.."
+ cd "$SCRIPTPATH/../../.."
scripts/integration.sh ~/"$template" dev
pkill -9 -f 'next-server|python3' || true
sleep 10
diff --git a/integration/shared/state.py b/tests/integration/shared/state.py
similarity index 99%
rename from integration/shared/state.py
rename to tests/integration/shared/state.py
index e3aaf62d3..be6aa1f2a 100644
--- a/integration/shared/state.py
+++ b/tests/integration/shared/state.py
@@ -1,4 +1,5 @@
"""Simple module which contains one reusable reflex state class."""
+
import reflex as rx
diff --git a/integration/test_background_task.py b/tests/integration/test_background_task.py
similarity index 51%
rename from integration/test_background_task.py
rename to tests/integration/test_background_task.py
index 5edf810f4..87aa1459b 100644
--- a/integration/test_background_task.py
+++ b/tests/integration/test_background_task.py
@@ -1,4 +1,4 @@
-"""Test @rx.background task functionality."""
+"""Test @rx.event(background=True) task functionality."""
from typing import Generator
@@ -12,14 +12,17 @@ def BackgroundTask():
"""Test that background tasks work as expected."""
import asyncio
+ import pytest
+
import reflex as rx
+ from reflex.state import ImmutableStateError
class State(rx.State):
counter: int = 0
_task_id: int = 0
iterations: int = 10
- @rx.background
+ @rx.event(background=True)
async def handle_event(self):
async with self:
self._task_id += 1
@@ -28,7 +31,7 @@ def BackgroundTask():
self.counter += 1
await asyncio.sleep(0.005)
- @rx.background
+ @rx.event(background=True)
async def handle_event_yield_only(self):
async with self:
self._task_id += 1
@@ -39,31 +42,87 @@ def BackgroundTask():
yield State.increment() # type: ignore
await asyncio.sleep(0.005)
+ @rx.event
def increment(self):
self.counter += 1
- @rx.background
+ @rx.event(background=True)
async def increment_arbitrary(self, amount: int):
async with self:
self.counter += int(amount)
+ @rx.event
def reset_counter(self):
self.counter = 0
+ @rx.event
async def blocking_pause(self):
await asyncio.sleep(0.02)
- @rx.background
+ @rx.event(background=True)
async def non_blocking_pause(self):
await asyncio.sleep(0.02)
+ async def racy_task(self):
+ async with self:
+ self._task_id += 1
+ for _ix in range(int(self.iterations)):
+ async with self:
+ self.counter += 1
+ await asyncio.sleep(0.005)
+
+ @rx.event(background=True)
+ async def handle_racy_event(self):
+ await asyncio.gather(
+ self.racy_task(), self.racy_task(), self.racy_task(), self.racy_task()
+ )
+
+ @rx.event(background=True)
+ async def nested_async_with_self(self):
+ async with self:
+ self.counter += 1
+ with pytest.raises(ImmutableStateError):
+ async with self:
+ self.counter += 1
+
+ async def triple_count(self):
+ third_state = await self.get_state(ThirdState)
+ await third_state._triple_count()
+
+ @rx.event(background=True)
+ async def yield_in_async_with_self(self):
+ async with self:
+ self.counter += 1
+ yield
+ self.counter += 1
+
+ class OtherState(rx.State):
+ @rx.event(background=True)
+ async def get_other_state(self):
+ async with self:
+ state = await self.get_state(State)
+ state.counter += 1
+ await state.triple_count()
+ with pytest.raises(ImmutableStateError):
+ await state.triple_count()
+ with pytest.raises(ImmutableStateError):
+ state.counter += 1
+ async with state:
+ state.counter += 1
+ await state.triple_count()
+
+ class ThirdState(rx.State):
+ async def _triple_count(self):
+ state = await self.get_state(State)
+ state.counter *= 3
+
def index() -> rx.Component:
return rx.vstack(
- rx.chakra.input(
+ rx.input(
id="token", value=State.router.session.client_token, is_read_only=True
),
rx.heading(State.counter, id="counter"),
- rx.chakra.input(
+ rx.input(
id="iterations",
placeholder="Iterations",
value=State.iterations.to_string(), # type: ignore
@@ -90,6 +149,26 @@ def BackgroundTask():
on_click=State.non_blocking_pause,
id="non-blocking-pause",
),
+ rx.button(
+ "Racy Increment (x4)",
+ on_click=State.handle_racy_event,
+ id="racy-increment",
+ ),
+ rx.button(
+ "Nested Async with Self",
+ on_click=State.nested_async_with_self,
+ id="nested-async-with-self",
+ ),
+ rx.button(
+ "Increment from OtherState",
+ on_click=OtherState.get_other_state,
+ id="increment-from-other-state",
+ ),
+ rx.button(
+ "Yield in Async with Self",
+ on_click=State.yield_in_async_with_self,
+ id="yield-in-async-with-self",
+ ),
rx.button("Reset", on_click=State.reset_counter, id="reset"),
)
@@ -176,6 +255,7 @@ def test_background_task(
increment_button = driver.find_element(By.ID, "increment")
blocking_pause_button = driver.find_element(By.ID, "blocking-pause")
non_blocking_pause_button = driver.find_element(By.ID, "non-blocking-pause")
+ racy_increment_button = driver.find_element(By.ID, "racy-increment")
driver.find_element(By.ID, "reset")
# get a reference to the counter
@@ -196,6 +276,7 @@ def test_background_task(
delayed_increment_button.click()
delayed_increment_button.click()
yield_increment_button.click()
+ racy_increment_button.click()
non_blocking_pause_button.click()
yield_increment_button.click()
blocking_pause_button.click()
@@ -204,8 +285,93 @@ def test_background_task(
increment_button.click()
yield_increment_button.click()
blocking_pause_button.click()
- assert background_task._poll_for(lambda: counter.text == "420", timeout=40)
+ assert background_task._poll_for(lambda: counter.text == "620", timeout=40)
# all tasks should have exited and cleaned up
assert background_task._poll_for(
lambda: not background_task.app_instance.background_tasks # type: ignore
)
+
+
+def test_nested_async_with_self(
+ background_task: AppHarness,
+ driver: WebDriver,
+ token: str,
+):
+ """Test that nested async with self in the same coroutine raises Exception.
+
+ Args:
+ background_task: harness for BackgroundTask app.
+ driver: WebDriver instance.
+ token: The token for the connected client.
+ """
+ assert background_task.app_instance is not None
+
+ # get a reference to all buttons
+ nested_async_with_self_button = driver.find_element(By.ID, "nested-async-with-self")
+ increment_button = driver.find_element(By.ID, "increment")
+
+ # get a reference to the counter
+ counter = driver.find_element(By.ID, "counter")
+ assert background_task._poll_for(lambda: counter.text == "0", timeout=5)
+
+ nested_async_with_self_button.click()
+ assert background_task._poll_for(lambda: counter.text == "1", timeout=5)
+
+ increment_button.click()
+ assert background_task._poll_for(lambda: counter.text == "2", timeout=5)
+
+
+def test_get_state(
+ background_task: AppHarness,
+ driver: WebDriver,
+ token: str,
+):
+ """Test that get_state returns a state bound to the correct StateProxy.
+
+ Args:
+ background_task: harness for BackgroundTask app.
+ driver: WebDriver instance.
+ token: The token for the connected client.
+ """
+ assert background_task.app_instance is not None
+
+ # get a reference to all buttons
+ other_state_button = driver.find_element(By.ID, "increment-from-other-state")
+ increment_button = driver.find_element(By.ID, "increment")
+
+ # get a reference to the counter
+ counter = driver.find_element(By.ID, "counter")
+ assert background_task._poll_for(lambda: counter.text == "0", timeout=5)
+
+ other_state_button.click()
+ assert background_task._poll_for(lambda: counter.text == "12", timeout=5)
+
+ increment_button.click()
+ assert background_task._poll_for(lambda: counter.text == "13", timeout=5)
+
+
+def test_yield_in_async_with_self(
+ background_task: AppHarness,
+ driver: WebDriver,
+ token: str,
+):
+ """Test that yielding inside async with self does not disable mutability.
+
+ Args:
+ background_task: harness for BackgroundTask app.
+ driver: WebDriver instance.
+ token: The token for the connected client.
+ """
+ assert background_task.app_instance is not None
+
+ # get a reference to all buttons
+ yield_in_async_with_self_button = driver.find_element(
+ By.ID, "yield-in-async-with-self"
+ )
+
+ # get a reference to the counter
+ counter = driver.find_element(By.ID, "counter")
+ assert background_task._poll_for(lambda: counter.text == "0", timeout=5)
+
+ yield_in_async_with_self_button.click()
+ assert background_task._poll_for(lambda: counter.text == "2", timeout=5)
diff --git a/integration/test_call_script.py b/tests/integration/test_call_script.py
similarity index 60%
rename from integration/test_call_script.py
rename to tests/integration/test_call_script.py
index 18e66cff5..a949dc451 100644
--- a/integration/test_call_script.py
+++ b/tests/integration/test_call_script.py
@@ -1,4 +1,5 @@
"""Integration tests for client side storage."""
+
from __future__ import annotations
from typing import Generator
@@ -9,6 +10,8 @@ from selenium.webdriver.remote.webdriver import WebDriver
from reflex.testing import AppHarness
+from .utils import SessionStorage
+
def CallScript():
"""A test app for browser javascript integration."""
@@ -42,6 +45,8 @@ def CallScript():
results: List[Optional[Union[str, Dict, List]]] = []
inline_counter: int = 0
external_counter: int = 0
+ value: str = "Initial"
+ last_result: str = ""
def call_script_callback(self, result):
self.results.append(result)
@@ -49,15 +54,18 @@ def CallScript():
def call_script_callback_other_arg(self, result, other_arg):
self.results.append([other_arg, result])
+ @rx.event
def call_scripts_inline_yield(self):
yield rx.call_script("inline1()")
yield rx.call_script("inline2()")
yield rx.call_script("inline3()")
yield rx.call_script("inline4()")
+ @rx.event
def call_script_inline_return(self):
return rx.call_script("inline2()")
+ @rx.event
def call_scripts_inline_yield_callback(self):
yield rx.call_script(
"inline1()", callback=CallScriptState.call_script_callback
@@ -72,11 +80,13 @@ def CallScript():
"inline4()", callback=CallScriptState.call_script_callback
)
+ @rx.event
def call_script_inline_return_callback(self):
return rx.call_script(
"inline3()", callback=CallScriptState.call_script_callback
)
+ @rx.event
def call_script_inline_return_lambda(self):
return rx.call_script(
"inline2()",
@@ -85,21 +95,25 @@ def CallScript():
),
)
+ @rx.event
def get_inline_counter(self):
return rx.call_script(
"inline_counter",
callback=CallScriptState.set_inline_counter, # type: ignore
)
+ @rx.event
def call_scripts_external_yield(self):
yield rx.call_script("external1()")
yield rx.call_script("external2()")
yield rx.call_script("external3()")
yield rx.call_script("external4()")
+ @rx.event
def call_script_external_return(self):
return rx.call_script("external2()")
+ @rx.event
def call_scripts_external_yield_callback(self):
yield rx.call_script(
"external1()", callback=CallScriptState.call_script_callback
@@ -114,11 +128,13 @@ def CallScript():
"external4()", callback=CallScriptState.call_script_callback
)
+ @rx.event
def call_script_external_return_callback(self):
return rx.call_script(
"external3()", callback=CallScriptState.call_script_callback
)
+ @rx.event
def call_script_external_return_lambda(self):
return rx.call_script(
"external2()",
@@ -127,12 +143,44 @@ def CallScript():
),
)
+ @rx.event
def get_external_counter(self):
return rx.call_script(
"external_counter",
callback=CallScriptState.set_external_counter, # type: ignore
)
+ @rx.event
+ def call_with_var_f_string(self):
+ return rx.call_script(
+ f"{rx.Var('inline_counter')} + {rx.Var('external_counter')}",
+ callback=CallScriptState.set_last_result, # type: ignore
+ )
+
+ @rx.event
+ def call_with_var_str_cast(self):
+ return rx.call_script(
+ f"{str(rx.Var('inline_counter'))} + {str(rx.Var('external_counter'))}",
+ callback=CallScriptState.set_last_result, # type: ignore
+ )
+
+ @rx.event
+ def call_with_var_f_string_wrapped(self):
+ return rx.call_script(
+ rx.Var(f"{rx.Var('inline_counter')} + {rx.Var('external_counter')}"),
+ callback=CallScriptState.set_last_result, # type: ignore
+ )
+
+ @rx.event
+ def call_with_var_str_cast_wrapped(self):
+ return rx.call_script(
+ rx.Var(
+ f"{str(rx.Var('inline_counter'))} + {str(rx.Var('external_counter'))}"
+ ),
+ callback=CallScriptState.set_last_result, # type: ignore
+ )
+
+ @rx.event
def reset_(self):
yield rx.call_script("inline_counter = 0; external_counter = 0")
self.reset()
@@ -144,25 +192,20 @@ def CallScript():
@app.add_page
def index():
return rx.vstack(
- rx.chakra.input(
- value=CallScriptState.router.session.client_token,
- is_read_only=True,
- id="token",
- ),
- rx.chakra.input(
+ rx.input(
value=CallScriptState.inline_counter.to(str), # type: ignore
id="inline_counter",
- is_read_only=True,
+ read_only=True,
),
- rx.chakra.input(
+ rx.input(
value=CallScriptState.external_counter.to(str), # type: ignore
id="external_counter",
- is_read_only=True,
+ read_only=True,
),
rx.text_area(
value=CallScriptState.results.to_string(), # type: ignore
id="results",
- is_read_only=True,
+ read_only=True,
),
rx.script(inline_scripts),
rx.script(src="/external.js"),
@@ -226,7 +269,77 @@ def CallScript():
on_click=CallScriptState.get_external_counter,
id="update_external_counter",
),
+ rx.button(
+ CallScriptState.value,
+ on_click=rx.call_script(
+ "'updated'",
+ callback=CallScriptState.set_value, # type: ignore
+ ),
+ id="update_value",
+ ),
rx.button("Reset", id="reset", on_click=CallScriptState.reset_),
+ rx.input(
+ value=CallScriptState.last_result,
+ id="last_result",
+ read_only=True,
+ on_click=CallScriptState.set_last_result(""), # type: ignore
+ ),
+ rx.button(
+ "call_with_var_f_string",
+ on_click=CallScriptState.call_with_var_f_string,
+ id="call_with_var_f_string",
+ ),
+ rx.button(
+ "call_with_var_str_cast",
+ on_click=CallScriptState.call_with_var_str_cast,
+ id="call_with_var_str_cast",
+ ),
+ rx.button(
+ "call_with_var_f_string_wrapped",
+ on_click=CallScriptState.call_with_var_f_string_wrapped,
+ id="call_with_var_f_string_wrapped",
+ ),
+ rx.button(
+ "call_with_var_str_cast_wrapped",
+ on_click=CallScriptState.call_with_var_str_cast_wrapped,
+ id="call_with_var_str_cast_wrapped",
+ ),
+ rx.button(
+ "call_with_var_f_string_inline",
+ on_click=rx.call_script(
+ f"{rx.Var('inline_counter')} + {CallScriptState.last_result}",
+ callback=CallScriptState.set_last_result, # type: ignore
+ ),
+ id="call_with_var_f_string_inline",
+ ),
+ rx.button(
+ "call_with_var_str_cast_inline",
+ on_click=rx.call_script(
+ f"{str(rx.Var('inline_counter'))} + {str(rx.Var('external_counter'))}",
+ callback=CallScriptState.set_last_result, # type: ignore
+ ),
+ id="call_with_var_str_cast_inline",
+ ),
+ rx.button(
+ "call_with_var_f_string_wrapped_inline",
+ on_click=rx.call_script(
+ rx.Var(
+ f"{rx.Var('inline_counter')} + {CallScriptState.last_result}"
+ ),
+ callback=CallScriptState.set_last_result, # type: ignore
+ ),
+ id="call_with_var_f_string_wrapped_inline",
+ ),
+ rx.button(
+ "call_with_var_str_cast_wrapped_inline",
+ on_click=rx.call_script(
+ rx.Var(
+ f"{str(rx.Var('inline_counter'))} + {str(rx.Var('external_counter'))}"
+ ),
+ callback=CallScriptState.set_last_result, # type: ignore
+ ),
+ id="call_with_var_str_cast_wrapped_inline",
+ ),
)
@@ -265,25 +378,18 @@ def driver(call_script: AppHarness) -> Generator[WebDriver, None, None]:
driver.quit()
-def assert_token(call_script: AppHarness, driver: WebDriver) -> str:
+def assert_token(driver: WebDriver) -> str:
"""Get the token associated with backend state.
Args:
- call_script: harness for CallScript app.
driver: WebDriver instance.
Returns:
The token visible in the driver browser.
"""
- assert call_script.app_instance is not None
- token_input = driver.find_element(By.ID, "token")
- assert token_input
-
- # wait for the backend connection to send the token
- token = call_script.poll_for_value(token_input)
- assert token is not None
-
- return token
+ ss = SessionStorage(driver)
+ assert AppHarness._poll_for(lambda: ss.get("token") is not None), "token not found"
+ return ss.get("token")
@pytest.mark.parametrize("script", ["inline", "external"])
@@ -299,7 +405,7 @@ def test_call_script(
driver: WebDriver instance.
script: The type of script to test.
"""
- assert_token(call_script, driver)
+ assert_token(driver)
reset_button = driver.find_element(By.ID, "reset")
update_counter_button = driver.find_element(By.ID, f"update_{script}_counter")
counter = driver.find_element(By.ID, f"{script}_counter")
@@ -354,3 +460,82 @@ def test_call_script(
)
reset_button.click()
assert call_script.poll_for_value(counter, exp_not_equal="1") == "0"
+
+ # Check that triggering script from event trigger calls callback
+ update_value_button = driver.find_element(By.ID, "update_value")
+ update_value_button.click()
+
+ assert (
+ call_script.poll_for_content(update_value_button, exp_not_equal="Initial")
+ == "updated"
+ )
+
+
+def test_call_script_w_var(
+ call_script: AppHarness,
+ driver: WebDriver,
+):
+ """Test evaluating javascript expressions containing Vars.
+
+ Args:
+ call_script: harness for CallScript app.
+ driver: WebDriver instance.
+ """
+ assert_token(driver)
+ last_result = driver.find_element(By.ID, "last_result")
+ assert last_result.get_attribute("value") == ""
+
+ inline_return_button = driver.find_element(By.ID, "inline_return")
+
+ call_with_var_f_string_button = driver.find_element(By.ID, "call_with_var_f_string")
+ call_with_var_str_cast_button = driver.find_element(By.ID, "call_with_var_str_cast")
+ call_with_var_f_string_wrapped_button = driver.find_element(
+ By.ID, "call_with_var_f_string_wrapped"
+ )
+ call_with_var_str_cast_wrapped_button = driver.find_element(
+ By.ID, "call_with_var_str_cast_wrapped"
+ )
+ call_with_var_f_string_inline_button = driver.find_element(
+ By.ID, "call_with_var_f_string_inline"
+ )
+ call_with_var_str_cast_inline_button = driver.find_element(
+ By.ID, "call_with_var_str_cast_inline"
+ )
+ call_with_var_f_string_wrapped_inline_button = driver.find_element(
+ By.ID, "call_with_var_f_string_wrapped_inline"
+ )
+ call_with_var_str_cast_wrapped_inline_button = driver.find_element(
+ By.ID, "call_with_var_str_cast_wrapped_inline"
+ )
+
+ inline_return_button.click()
+ call_with_var_f_string_button.click()
+ assert call_script.poll_for_value(last_result, exp_not_equal="") == "1"
+
+ inline_return_button.click()
+ call_with_var_str_cast_button.click()
+ assert call_script.poll_for_value(last_result, exp_not_equal="1") == "2"
+
+ inline_return_button.click()
+ call_with_var_f_string_wrapped_button.click()
+ assert call_script.poll_for_value(last_result, exp_not_equal="2") == "3"
+
+ inline_return_button.click()
+ call_with_var_str_cast_wrapped_button.click()
+ assert call_script.poll_for_value(last_result, exp_not_equal="3") == "4"
+
+ inline_return_button.click()
+ call_with_var_f_string_inline_button.click()
+ assert call_script.poll_for_value(last_result, exp_not_equal="4") == "9"
+
+ inline_return_button.click()
+ call_with_var_str_cast_inline_button.click()
+ assert call_script.poll_for_value(last_result, exp_not_equal="9") == "6"
+
+ inline_return_button.click()
+ call_with_var_f_string_wrapped_inline_button.click()
+ assert call_script.poll_for_value(last_result, exp_not_equal="6") == "13"
+
+ inline_return_button.click()
+ call_with_var_str_cast_wrapped_inline_button.click()
+ assert call_script.poll_for_value(last_result, exp_not_equal="13") == "8"
diff --git a/integration/test_client_storage.py b/tests/integration/test_client_storage.py
similarity index 77%
rename from integration/test_client_storage.py
rename to tests/integration/test_client_storage.py
index 24c3c7be0..ae66087e2 100644
--- a/integration/test_client_storage.py
+++ b/tests/integration/test_client_storage.py
@@ -1,4 +1,5 @@
"""Integration tests for client side storage."""
+
from __future__ import annotations
import time
@@ -46,9 +47,15 @@ def ClientSide():
l5: str = rx.LocalStorage(sync=True)
l6: str = rx.LocalStorage(sync=True, name="l6")
+ # Session storage
+ s1: str = rx.SessionStorage()
+ s2: rx.SessionStorage = "s2 default" # type: ignore
+ s3: str = rx.SessionStorage(name="s3")
+
def set_l6(self, my_param: str):
self.l6 = my_param
+ @rx.event
def set_var(self):
setattr(self, self.state_var, self.input_value)
self.state_var = self.input_value = ""
@@ -56,25 +63,27 @@ def ClientSide():
class ClientSideSubSubState(ClientSideSubState):
c1s: str = rx.Cookie()
l1s: str = rx.LocalStorage()
+ s1s: str = rx.SessionStorage()
+ @rx.event
def set_var(self):
setattr(self, self.state_var, self.input_value)
self.state_var = self.input_value = ""
def index():
return rx.fragment(
- rx.chakra.input(
+ rx.input(
value=ClientSideState.router.session.client_token,
is_read_only=True,
id="token",
),
- rx.chakra.input(
+ rx.input(
placeholder="state var",
value=ClientSideState.state_var,
on_change=ClientSideState.set_state_var, # type: ignore
id="state_var",
),
- rx.chakra.input(
+ rx.input(
placeholder="input value",
value=ClientSideState.input_value,
on_change=ClientSideState.set_input_value, # type: ignore
@@ -103,8 +112,12 @@ def ClientSide():
rx.box(ClientSideSubState.l4, id="l4"),
rx.box(ClientSideSubState.l5, id="l5"),
rx.box(ClientSideSubState.l6, id="l6"),
+ rx.box(ClientSideSubState.s1, id="s1"),
+ rx.box(ClientSideSubState.s2, id="s2"),
+ rx.box(ClientSideSubState.s3, id="s3"),
rx.box(ClientSideSubSubState.c1s, id="c1s"),
rx.box(ClientSideSubSubState.l1s, id="l1s"),
+ rx.box(ClientSideSubSubState.s1s, id="s1s"),
)
app = rx.App(state=rx.State)
@@ -162,6 +175,21 @@ def local_storage(driver: WebDriver) -> Generator[utils.LocalStorage, None, None
ls.clear()
+@pytest.fixture()
+def session_storage(driver: WebDriver) -> Generator[utils.SessionStorage, None, None]:
+ """Get an instance of the session storage helper.
+
+ Args:
+ driver: WebDriver instance.
+
+ Yields:
+ Session storage helper.
+ """
+ ss = utils.SessionStorage(driver)
+ yield ss
+ ss.clear()
+
+
@pytest.fixture(autouse=True)
def delete_all_cookies(driver: WebDriver) -> Generator[None, None, None]:
"""Delete all cookies after each test.
@@ -190,7 +218,10 @@ def cookie_info_map(driver: WebDriver) -> dict[str, dict[str, str]]:
@pytest.mark.asyncio
async def test_client_side_state(
- client_side: AppHarness, driver: WebDriver, local_storage: utils.LocalStorage
+ client_side: AppHarness,
+ driver: WebDriver,
+ local_storage: utils.LocalStorage,
+ session_storage: utils.SessionStorage,
):
"""Test client side state.
@@ -198,8 +229,10 @@ async def test_client_side_state(
client_side: harness for ClientSide app.
driver: WebDriver instance.
local_storage: Local storage helper.
+ session_storage: Session storage helper.
"""
- assert client_side.app_instance is not None
+ app = client_side.app_instance
+ assert app is not None
assert client_side.frontend_url is not None
def poll_for_token():
@@ -251,8 +284,12 @@ async def test_client_side_state(
l2 = driver.find_element(By.ID, "l2")
l3 = driver.find_element(By.ID, "l3")
l4 = driver.find_element(By.ID, "l4")
+ s1 = driver.find_element(By.ID, "s1")
+ s2 = driver.find_element(By.ID, "s2")
+ s3 = driver.find_element(By.ID, "s3")
c1s = driver.find_element(By.ID, "c1s")
l1s = driver.find_element(By.ID, "l1s")
+ s1s = driver.find_element(By.ID, "s1s")
# assert on defaults where present
assert c1.text == ""
@@ -266,13 +303,17 @@ async def test_client_side_state(
assert l2.text == "l2 default"
assert l3.text == ""
assert l4.text == "l4 default"
+ assert s1.text == ""
+ assert s2.text == "s2 default"
+ assert s3.text == ""
assert c1s.text == ""
assert l1s.text == ""
+ assert s1s.text == ""
# no cookies should be set yet!
assert not driver.get_cookies()
local_storage_items = local_storage.items()
- local_storage_items.pop("chakra-ui-color-mode", None)
+ local_storage_items.pop("last_compiled_time", None)
assert not local_storage_items
# set some cookies and local storage values
@@ -287,32 +328,44 @@ async def test_client_side_state(
set_sub("l2", "l2 value")
set_sub("l3", "l3 value")
set_sub("l4", "l4 value")
+ set_sub("s1", "s1 value")
+ set_sub("s2", "s2 value")
+ set_sub("s3", "s3 value")
set_sub_sub("c1s", "c1s value")
set_sub_sub("l1s", "l1s value")
+ set_sub_sub("s1s", "s1s value")
+
+ state_name = client_side.get_full_state_name(["_client_side_state"])
+ sub_state_name = client_side.get_full_state_name(
+ ["_client_side_state", "_client_side_sub_state"]
+ )
+ sub_sub_state_name = client_side.get_full_state_name(
+ ["_client_side_state", "_client_side_sub_state", "_client_side_sub_sub_state"]
+ )
exp_cookies = {
- "state.client_side_state.client_side_sub_state.c1": {
+ f"{sub_state_name}.c1": {
"domain": "localhost",
"httpOnly": False,
- "name": "state.client_side_state.client_side_sub_state.c1",
+ "name": f"{sub_state_name}.c1",
"path": "/",
"sameSite": "Lax",
"secure": False,
"value": "c1%20value",
},
- "state.client_side_state.client_side_sub_state.c2": {
+ f"{sub_state_name}.c2": {
"domain": "localhost",
"httpOnly": False,
- "name": "state.client_side_state.client_side_sub_state.c2",
+ "name": f"{sub_state_name}.c2",
"path": "/",
"sameSite": "Lax",
"secure": False,
"value": "c2%20value",
},
- "state.client_side_state.client_side_sub_state.c4": {
+ f"{sub_state_name}.c4": {
"domain": "localhost",
"httpOnly": False,
- "name": "state.client_side_state.client_side_sub_state.c4",
+ "name": f"{sub_state_name}.c4",
"path": "/",
"sameSite": "Strict",
"secure": False,
@@ -327,19 +380,19 @@ async def test_client_side_state(
"secure": False,
"value": "c6%20value",
},
- "state.client_side_state.client_side_sub_state.c7": {
+ f"{sub_state_name}.c7": {
"domain": "localhost",
"httpOnly": False,
- "name": "state.client_side_state.client_side_sub_state.c7",
+ "name": f"{sub_state_name}.c7",
"path": "/",
"sameSite": "Lax",
"secure": False,
"value": "c7%20value",
},
- "state.client_side_state.client_side_sub_state.client_side_sub_sub_state.c1s": {
+ f"{sub_sub_state_name}.c1s": {
"domain": "localhost",
"httpOnly": False,
- "name": "state.client_side_state.client_side_sub_state.client_side_sub_sub_state.c1s",
+ "name": f"{sub_sub_state_name}.c1s",
"path": "/",
"sameSite": "Lax",
"secure": False,
@@ -357,18 +410,13 @@ async def test_client_side_state(
# Test cookie with expiry by itself to avoid timing flakiness
set_sub("c3", "c3 value")
- AppHarness._poll_for(
- lambda: "state.client_side_state.client_side_sub_state.c3"
- in cookie_info_map(driver)
- )
- c3_cookie = cookie_info_map(driver)[
- "state.client_side_state.client_side_sub_state.c3"
- ]
+ AppHarness._poll_for(lambda: f"{sub_state_name}.c3" in cookie_info_map(driver))
+ c3_cookie = cookie_info_map(driver)[f"{sub_state_name}.c3"]
assert c3_cookie.pop("expiry") is not None
assert c3_cookie == {
"domain": "localhost",
"httpOnly": False,
- "name": "state.client_side_state.client_side_sub_state.c3",
+ "name": f"{sub_state_name}.c3",
"path": "/",
"sameSite": "Lax",
"secure": False,
@@ -377,34 +425,25 @@ async def test_client_side_state(
time.sleep(2) # wait for c3 to expire
if not isinstance(driver, Firefox):
# Note: Firefox does not remove expired cookies Bug 576347
- assert (
- "state.client_side_state.client_side_sub_state.c3"
- not in cookie_info_map(driver)
- )
+ assert f"{sub_state_name}.c3" not in cookie_info_map(driver)
local_storage_items = local_storage.items()
- local_storage_items.pop("chakra-ui-color-mode", None)
- assert (
- local_storage_items.pop("state.client_side_state.client_side_sub_state.l1")
- == "l1 value"
- )
- assert (
- local_storage_items.pop("state.client_side_state.client_side_sub_state.l2")
- == "l2 value"
- )
+ local_storage_items.pop("last_compiled_time", None)
+ assert local_storage_items.pop(f"{sub_state_name}.l1") == "l1 value"
+ assert local_storage_items.pop(f"{sub_state_name}.l2") == "l2 value"
assert local_storage_items.pop("l3") == "l3 value"
- assert (
- local_storage_items.pop("state.client_side_state.client_side_sub_state.l4")
- == "l4 value"
- )
- assert (
- local_storage_items.pop(
- "state.client_side_state.client_side_sub_state.client_side_sub_sub_state.l1s"
- )
- == "l1s value"
- )
+ assert local_storage_items.pop(f"{sub_state_name}.l4") == "l4 value"
+ assert local_storage_items.pop(f"{sub_sub_state_name}.l1s") == "l1s value"
assert not local_storage_items
+ session_storage_items = session_storage.items()
+ session_storage_items.pop("token", None)
+ assert session_storage_items.pop(f"{sub_state_name}.s1") == "s1 value"
+ assert session_storage_items.pop(f"{sub_state_name}.s2") == "s2 value"
+ assert session_storage_items.pop("s3") == "s3 value"
+ assert session_storage_items.pop(f"{sub_sub_state_name}.s1s") == "s1s value"
+ assert not session_storage_items
+
assert c1.text == "c1 value"
assert c2.text == "c2 value"
assert c3.text == "c3 value"
@@ -416,8 +455,12 @@ async def test_client_side_state(
assert l2.text == "l2 value"
assert l3.text == "l3 value"
assert l4.text == "l4 value"
+ assert s1.text == "s1 value"
+ assert s2.text == "s2 value"
+ assert s3.text == "s3 value"
assert c1s.text == "c1s value"
assert l1s.text == "l1s value"
+ assert s1s.text == "s1s value"
# navigate to the /foo route
with utils.poll_for_navigation(driver):
@@ -435,8 +478,12 @@ async def test_client_side_state(
l2 = driver.find_element(By.ID, "l2")
l3 = driver.find_element(By.ID, "l3")
l4 = driver.find_element(By.ID, "l4")
+ s1 = driver.find_element(By.ID, "s1")
+ s2 = driver.find_element(By.ID, "s2")
+ s3 = driver.find_element(By.ID, "s3")
c1s = driver.find_element(By.ID, "c1s")
l1s = driver.find_element(By.ID, "l1s")
+ s1s = driver.find_element(By.ID, "s1s")
assert c1.text == "c1 value"
assert c2.text == "c2 value"
@@ -449,11 +496,15 @@ async def test_client_side_state(
assert l2.text == "l2 value"
assert l3.text == "l3 value"
assert l4.text == "l4 value"
+ assert s1.text == "s1 value"
+ assert s2.text == "s2 value"
+ assert s3.text == "s3 value"
assert c1s.text == "c1s value"
assert l1s.text == "l1s value"
+ assert s1s.text == "s1s value"
# reset the backend state to force refresh from client storage
- async with client_side.modify_state(f"{token}_state.client_side_state") as state:
+ async with client_side.modify_state(f"{token}_{state_name}") as state:
state.reset()
driver.refresh()
@@ -475,8 +526,12 @@ async def test_client_side_state(
l2 = driver.find_element(By.ID, "l2")
l3 = driver.find_element(By.ID, "l3")
l4 = driver.find_element(By.ID, "l4")
+ s1 = driver.find_element(By.ID, "s1")
+ s2 = driver.find_element(By.ID, "s2")
+ s3 = driver.find_element(By.ID, "s3")
c1s = driver.find_element(By.ID, "c1s")
l1s = driver.find_element(By.ID, "l1s")
+ s1s = driver.find_element(By.ID, "s1s")
assert c1.text == "c1 value"
assert c2.text == "c2 value"
@@ -489,20 +544,19 @@ async def test_client_side_state(
assert l2.text == "l2 value"
assert l3.text == "l3 value"
assert l4.text == "l4 value"
+ assert s1.text == "s1 value"
+ assert s2.text == "s2 value"
+ assert s3.text == "s3 value"
assert c1s.text == "c1s value"
assert l1s.text == "l1s value"
+ assert s1s.text == "s1s value"
# make sure c5 cookie shows up on the `/foo` route
- AppHarness._poll_for(
- lambda: "state.client_side_state.client_side_sub_state.c5"
- in cookie_info_map(driver)
- )
- assert cookie_info_map(driver)[
- "state.client_side_state.client_side_sub_state.c5"
- ] == {
+ AppHarness._poll_for(lambda: f"{sub_state_name}.c5" in cookie_info_map(driver))
+ assert cookie_info_map(driver)[f"{sub_state_name}.c5"] == {
"domain": "localhost",
"httpOnly": False,
- "name": "state.client_side_state.client_side_sub_state.c5",
+ "name": f"{sub_state_name}.c5",
"path": "/foo/",
"sameSite": "Lax",
"secure": False,
@@ -525,6 +579,15 @@ async def test_client_side_state(
assert AppHarness._poll_for(lambda: l6.text == "l6 value")
assert l5.text == "l5 value"
+ # Set session storage values in the new tab
+ set_sub("s1", "other tab s1")
+ s1 = driver.find_element(By.ID, "s1")
+ s2 = driver.find_element(By.ID, "s2")
+ s3 = driver.find_element(By.ID, "s3")
+ assert AppHarness._poll_for(lambda: s1.text == "other tab s1")
+ assert s2.text == "s2 default"
+ assert s3.text == ""
+
# Switch back to main window.
driver.switch_to.window(main_tab)
@@ -534,6 +597,13 @@ async def test_client_side_state(
assert AppHarness._poll_for(lambda: l6.text == "l6 value")
assert l5.text == "l5 value"
+ s1 = driver.find_element(By.ID, "s1")
+ s2 = driver.find_element(By.ID, "s2")
+ s3 = driver.find_element(By.ID, "s3")
+ assert AppHarness._poll_for(lambda: s1.text == "s1 value")
+ assert s2.text == "s2 value"
+ assert s3.text == "s3 value"
+
# clear the cookie jar and local storage, ensure state reset to default
driver.delete_all_cookies()
local_storage.clear()
diff --git a/tests/integration/test_component_state.py b/tests/integration/test_component_state.py
new file mode 100644
index 000000000..f4a295d07
--- /dev/null
+++ b/tests/integration/test_component_state.py
@@ -0,0 +1,204 @@
+"""Test that per-component state scaffold works and operates independently."""
+
+from typing import Generator
+
+import pytest
+from selenium.webdriver.common.by import By
+
+from reflex.state import State, _substate_key
+from reflex.testing import AppHarness
+
+from . import utils
+
+
+def ComponentStateApp():
+ """App using per component state."""
+ from typing import Generic, TypeVar
+
+ import reflex as rx
+
+ E = TypeVar("E")
+
+ class MultiCounter(rx.ComponentState, Generic[E]):
+ """ComponentState style."""
+
+ count: int = 0
+ _be: E
+ _be_int: int
+ _be_str: str = "42"
+
+ @rx.event
+ def increment(self):
+ self.count += 1
+ self._be = self.count # type: ignore
+
+ @classmethod
+ def get_component(cls, *children, **props):
+ return rx.vstack(
+ *children,
+ rx.heading(cls.count, id=f"count-{props.get('id', 'default')}"),
+ rx.button(
+ "Increment",
+ on_click=cls.increment,
+ id=f"button-{props.get('id', 'default')}",
+ ),
+ **props,
+ )
+
+ def multi_counter_func(id: str = "default") -> rx.Component:
+ """Local-substate style.
+
+ Args:
+ id: identifier for this instance
+
+ Returns:
+ A new instance of the component with its own state.
+ """
+
+ class _Counter(rx.State):
+ count: int = 0
+
+ @rx.event
+ def increment(self):
+ self.count += 1
+
+ return rx.vstack(
+ rx.heading(_Counter.count, id=f"count-{id}"),
+ rx.button(
+ "Increment",
+ on_click=_Counter.increment,
+ id=f"button-{id}",
+ ),
+ State=_Counter,
+ )
+
+ app = rx.App(state=rx.State) # noqa
+
+ @rx.page()
+ def index():
+ mc_a = MultiCounter.create(id="a")
+ mc_b = MultiCounter.create(id="b")
+ mc_c = multi_counter_func(id="c")
+ mc_d = multi_counter_func(id="d")
+ assert mc_a.State != mc_b.State
+ assert mc_c.State != mc_d.State
+ return rx.vstack(
+ mc_a,
+ mc_b,
+ mc_c,
+ mc_d,
+ rx.button(
+ "Inc A",
+ on_click=mc_a.State.increment, # type: ignore
+ id="inc-a",
+ ),
+ rx.text(
+ mc_a.State.get_name() if mc_a.State is not None else "",
+ id="a_state_name",
+ ),
+ rx.text(
+ mc_b.State.get_name() if mc_b.State is not None else "",
+ id="b_state_name",
+ ),
+ )
+
+
+@pytest.fixture()
+def component_state_app(tmp_path) -> Generator[AppHarness, None, None]:
+ """Start ComponentStateApp app at tmp_path via AppHarness.
+
+ Args:
+ tmp_path: pytest tmp_path fixture
+
+ Yields:
+ running AppHarness instance
+ """
+ with AppHarness.create(
+ root=tmp_path,
+ app_source=ComponentStateApp, # type: ignore
+ ) as harness:
+ yield harness
+
+
+@pytest.mark.asyncio
+async def test_component_state_app(component_state_app: AppHarness):
+ """Increment counters independently.
+
+ Args:
+ component_state_app: harness for ComponentStateApp app
+ """
+ assert component_state_app.app_instance is not None, "app is not running"
+ driver = component_state_app.frontend()
+
+ ss = utils.SessionStorage(driver)
+ assert AppHarness._poll_for(lambda: ss.get("token") is not None), "token not found"
+ root_state_token = _substate_key(ss.get("token"), State)
+
+ count_a = driver.find_element(By.ID, "count-a")
+ count_b = driver.find_element(By.ID, "count-b")
+ button_a = driver.find_element(By.ID, "button-a")
+ button_b = driver.find_element(By.ID, "button-b")
+ button_inc_a = driver.find_element(By.ID, "inc-a")
+
+ # Check that backend vars in mixins are okay
+ a_state_name = driver.find_element(By.ID, "a_state_name").text
+ b_state_name = driver.find_element(By.ID, "b_state_name").text
+ root_state = await component_state_app.get_state(root_state_token)
+ a_state = root_state.substates[a_state_name]
+ b_state = root_state.substates[b_state_name]
+ assert a_state._backend_vars == a_state.backend_vars
+ assert a_state._backend_vars == b_state._backend_vars
+ assert a_state._backend_vars["_be"] is None
+ assert a_state._backend_vars["_be_int"] == 0
+ assert a_state._backend_vars["_be_str"] == "42"
+
+ assert count_a.text == "0"
+
+ button_a.click()
+ assert component_state_app.poll_for_content(count_a, exp_not_equal="0") == "1"
+
+ button_a.click()
+ assert component_state_app.poll_for_content(count_a, exp_not_equal="1") == "2"
+
+ button_inc_a.click()
+ assert component_state_app.poll_for_content(count_a, exp_not_equal="2") == "3"
+
+ root_state = await component_state_app.get_state(root_state_token)
+ a_state = root_state.substates[a_state_name]
+ b_state = root_state.substates[b_state_name]
+ assert a_state._backend_vars != a_state.backend_vars
+ assert a_state._be == a_state._backend_vars["_be"] == 3
+ assert b_state._be is None
+ assert b_state._backend_vars["_be"] is None
+
+ assert count_b.text == "0"
+
+ button_b.click()
+ assert component_state_app.poll_for_content(count_b, exp_not_equal="0") == "1"
+
+ button_b.click()
+ assert component_state_app.poll_for_content(count_b, exp_not_equal="1") == "2"
+
+ root_state = await component_state_app.get_state(root_state_token)
+ a_state = root_state.substates[a_state_name]
+ b_state = root_state.substates[b_state_name]
+ assert b_state._backend_vars != b_state.backend_vars
+ assert b_state._be == b_state._backend_vars["_be"] == 2
+
+ # Check locally-defined substate style
+ count_c = driver.find_element(By.ID, "count-c")
+ count_d = driver.find_element(By.ID, "count-d")
+ button_c = driver.find_element(By.ID, "button-c")
+ button_d = driver.find_element(By.ID, "button-d")
+
+ assert component_state_app.poll_for_content(count_c, exp_not_equal="") == "0"
+ assert component_state_app.poll_for_content(count_d, exp_not_equal="") == "0"
+ button_c.click()
+ assert component_state_app.poll_for_content(count_c, exp_not_equal="0") == "1"
+ assert component_state_app.poll_for_content(count_d, exp_not_equal="") == "0"
+ button_c.click()
+ assert component_state_app.poll_for_content(count_c, exp_not_equal="1") == "2"
+ assert component_state_app.poll_for_content(count_d, exp_not_equal="") == "0"
+ button_d.click()
+ assert component_state_app.poll_for_content(count_c, exp_not_equal="1") == "2"
+ assert component_state_app.poll_for_content(count_d, exp_not_equal="0") == "1"
diff --git a/tests/integration/test_computed_vars.py b/tests/integration/test_computed_vars.py
new file mode 100644
index 000000000..1f585cd8b
--- /dev/null
+++ b/tests/integration/test_computed_vars.py
@@ -0,0 +1,259 @@
+"""Test computed vars."""
+
+from __future__ import annotations
+
+import time
+from typing import Generator
+
+import pytest
+from selenium.webdriver.common.by import By
+
+from reflex.testing import DEFAULT_TIMEOUT, AppHarness, WebDriver
+
+
+def ComputedVars():
+ """Test app for computed vars."""
+ import reflex as rx
+
+ class StateMixin(rx.State, mixin=True):
+ pass
+
+ class State(StateMixin, rx.State):
+ count: int = 0
+
+ # cached var with dep on count
+ @rx.var(cache=True, interval=15)
+ def count1(self) -> int:
+ return self.count
+
+ # cached backend var with dep on count
+ @rx.var(cache=True, interval=15, backend=True)
+ def count1_backend(self) -> int:
+ return self.count
+
+ # same as above but implicit backend with `_` prefix
+ @rx.var(cache=True, interval=15)
+ def _count1_backend(self) -> int:
+ return self.count
+
+ # explicit disabled auto_deps
+ @rx.var(interval=15, cache=True, auto_deps=False)
+ def count3(self) -> int:
+ # this will not add deps, because auto_deps is False
+ print(self.count1)
+
+ return self.count
+
+ # explicit dependency on count var
+ @rx.var(cache=True, deps=["count"], auto_deps=False)
+ def depends_on_count(self) -> int:
+ return self.count
+
+ # explicit dependency on count1 var
+ @rx.var(cache=True, deps=[count1], auto_deps=False)
+ def depends_on_count1(self) -> int:
+ return self.count
+
+ @rx.var(deps=[count3], auto_deps=False, cache=True)
+ def depends_on_count3(self) -> int:
+ return self.count
+
+ @rx.event
+ def increment(self):
+ self.count += 1
+
+ @rx.event
+ def mark_dirty(self):
+ self._mark_dirty()
+
+ assert State.backend_vars == {}
+
+ def index() -> rx.Component:
+ return rx.center(
+ rx.vstack(
+ rx.input(
+ id="token",
+ value=State.router.session.client_token,
+ is_read_only=True,
+ ),
+ rx.button("Increment", on_click=State.increment, id="increment"),
+ rx.button("Do nothing", on_click=State.mark_dirty, id="mark_dirty"),
+ rx.text("count:"),
+ rx.text(State.count, id="count"),
+ rx.text("count1:"),
+ rx.text(State.count1, id="count1"),
+ rx.text("count1_backend:"),
+ rx.text(State.count1_backend, id="count1_backend"),
+ rx.text("_count1_backend:"),
+ rx.text(State._count1_backend, id="_count1_backend"),
+ rx.text("count3:"),
+ rx.text(State.count3, id="count3"),
+ rx.text("depends_on_count:"),
+ rx.text(
+ State.depends_on_count,
+ id="depends_on_count",
+ ),
+ rx.text("depends_on_count1:"),
+ rx.text(
+ State.depends_on_count1,
+ id="depends_on_count1",
+ ),
+ rx.text("depends_on_count3:"),
+ rx.text(
+ State.depends_on_count3,
+ id="depends_on_count3",
+ ),
+ ),
+ )
+
+ # raise Exception(State.count3._deps(objclass=State))
+ app = rx.App()
+ app.add_page(index)
+
+
+@pytest.fixture(scope="module")
+def computed_vars(
+ tmp_path_factory: pytest.TempPathFactory,
+) -> Generator[AppHarness, None, None]:
+ """Start ComputedVars app at tmp_path via AppHarness.
+
+ Args:
+ tmp_path_factory: pytest tmp_path_factory fixture
+
+ Yields:
+ running AppHarness instance
+ """
+ with AppHarness.create(
+ root=tmp_path_factory.mktemp(f"computed_vars"),
+ app_source=ComputedVars, # type: ignore
+ ) as harness:
+ yield harness
+
+
+@pytest.fixture
+def driver(computed_vars: AppHarness) -> Generator[WebDriver, None, None]:
+ """Get an instance of the browser open to the computed_vars app.
+
+ Args:
+ computed_vars: harness for ComputedVars app
+
+ Yields:
+ WebDriver instance.
+ """
+ assert computed_vars.app_instance is not None, "app is not running"
+ driver = computed_vars.frontend()
+ try:
+ yield driver
+ finally:
+ driver.quit()
+
+
+@pytest.fixture()
+def token(computed_vars: AppHarness, driver: WebDriver) -> str:
+ """Get a function that returns the active token.
+
+ Args:
+ computed_vars: harness for ComputedVars app.
+ driver: WebDriver instance.
+
+ Returns:
+ The token for the connected client
+ """
+ assert computed_vars.app_instance is not None
+ token_input = driver.find_element(By.ID, "token")
+ assert token_input
+
+ # wait for the backend connection to send the token
+ token = computed_vars.poll_for_value(token_input, timeout=DEFAULT_TIMEOUT * 2)
+ assert token is not None
+
+ return token
+
+
+@pytest.mark.asyncio
+async def test_computed_vars(
+ computed_vars: AppHarness,
+ driver: WebDriver,
+ token: str,
+):
+ """Test that computed vars are working as expected.
+
+ Args:
+ computed_vars: harness for ComputedVars app.
+ driver: WebDriver instance.
+ token: The token for the connected client.
+ """
+ assert computed_vars.app_instance is not None
+
+ state_name = computed_vars.get_state_name("_state")
+ full_state_name = computed_vars.get_full_state_name(["_state"])
+ token = f"{token}_{full_state_name}"
+ state = (await computed_vars.get_state(token)).substates[state_name]
+ assert state is not None
+ assert state.count1_backend == 0
+ assert state._count1_backend == 0
+
+ # test that backend var is not rendered
+ count1_backend = driver.find_element(By.ID, "count1_backend")
+ assert count1_backend
+ assert count1_backend.text == ""
+ _count1_backend = driver.find_element(By.ID, "_count1_backend")
+ assert _count1_backend
+ assert _count1_backend.text == ""
+
+ count = driver.find_element(By.ID, "count")
+ assert count
+ assert count.text == "0"
+
+ count1 = driver.find_element(By.ID, "count1")
+ assert count1
+ assert count1.text == "0"
+
+ count3 = driver.find_element(By.ID, "count3")
+ assert count3
+ assert count3.text == "0"
+
+ depends_on_count = driver.find_element(By.ID, "depends_on_count")
+ assert depends_on_count
+ assert depends_on_count.text == "0"
+
+ depends_on_count1 = driver.find_element(By.ID, "depends_on_count1")
+ assert depends_on_count1
+ assert depends_on_count1.text == "0"
+
+ depends_on_count3 = driver.find_element(By.ID, "depends_on_count3")
+ assert depends_on_count3
+ assert depends_on_count3.text == "0"
+
+ increment = driver.find_element(By.ID, "increment")
+ assert increment.is_enabled()
+
+ mark_dirty = driver.find_element(By.ID, "mark_dirty")
+ assert mark_dirty.is_enabled()
+
+ mark_dirty.click()
+
+ increment.click()
+ assert computed_vars.poll_for_content(count, timeout=2, exp_not_equal="0") == "1"
+ assert computed_vars.poll_for_content(count1, timeout=2, exp_not_equal="0") == "1"
+ assert (
+ computed_vars.poll_for_content(depends_on_count, timeout=2, exp_not_equal="0")
+ == "1"
+ )
+ state = (await computed_vars.get_state(token)).substates[state_name]
+ assert state is not None
+ assert state.count1_backend == 1
+ assert count1_backend.text == ""
+ assert state._count1_backend == 1
+ assert _count1_backend.text == ""
+
+ mark_dirty.click()
+ with pytest.raises(TimeoutError):
+ _ = computed_vars.poll_for_content(count3, timeout=5, exp_not_equal="0")
+
+ time.sleep(10)
+ assert count3.text == "0"
+ assert depends_on_count3.text == "0"
+ mark_dirty.click()
+ assert computed_vars.poll_for_content(count3, timeout=2, exp_not_equal="0") == "1"
+ assert depends_on_count3.text == "1"
diff --git a/integration/test_connection_banner.py b/tests/integration/test_connection_banner.py
similarity index 51%
rename from integration/test_connection_banner.py
rename to tests/integration/test_connection_banner.py
index 293d2e412..6921444b0 100644
--- a/integration/test_connection_banner.py
+++ b/tests/integration/test_connection_banner.py
@@ -8,16 +8,33 @@ from selenium.webdriver.common.by import By
from reflex.testing import AppHarness, WebDriver
+from .utils import SessionStorage
+
def ConnectionBanner():
"""App with a connection banner."""
+ import asyncio
+
import reflex as rx
class State(rx.State):
foo: int = 0
+ @rx.event
+ async def delay(self):
+ await asyncio.sleep(5)
+
def index():
- return rx.text("Hello World")
+ return rx.vstack(
+ rx.text("Hello World"),
+ rx.input(value=State.foo, read_only=True, id="counter"),
+ rx.button(
+ "Increment",
+ id="increment",
+ on_click=State.set_foo(State.foo + 1), # type: ignore
+ ),
+ rx.button("Delay", id="delay", on_click=State.delay),
+ )
app = rx.App(state=rx.State)
app.add_page(index)
@@ -40,7 +57,7 @@ def connection_banner(tmp_path) -> Generator[AppHarness, None, None]:
yield harness
-CONNECTION_ERROR_XPATH = "//*[ text() = 'Connection Error' ]"
+CONNECTION_ERROR_XPATH = "//*[ contains(text(), 'Cannot connect to server') ]"
def has_error_modal(driver: WebDriver) -> bool:
@@ -59,7 +76,8 @@ def has_error_modal(driver: WebDriver) -> bool:
return False
-def test_connection_banner(connection_banner: AppHarness):
+@pytest.mark.asyncio
+async def test_connection_banner(connection_banner: AppHarness):
"""Test that the connection banner is displayed when the websocket drops.
Args:
@@ -69,7 +87,23 @@ def test_connection_banner(connection_banner: AppHarness):
assert connection_banner.backend is not None
driver = connection_banner.frontend()
- connection_banner._poll_for(lambda: not has_error_modal(driver))
+ ss = SessionStorage(driver)
+ assert connection_banner._poll_for(
+ lambda: ss.get("token") is not None
+ ), "token not found"
+
+ assert connection_banner._poll_for(lambda: not has_error_modal(driver))
+
+ delay_button = driver.find_element(By.ID, "delay")
+ increment_button = driver.find_element(By.ID, "increment")
+ counter_element = driver.find_element(By.ID, "counter")
+
+ # Increment the counter
+ increment_button.click()
+ assert connection_banner.poll_for_value(counter_element, exp_not_equal="0") == "1"
+
+ # Start an long event before killing the backend, to mark event_processing=true
+ delay_button.click()
# Get the backend port
backend_port = connection_banner._poll_for_servers().getsockname()[1]
@@ -80,10 +114,20 @@ def test_connection_banner(connection_banner: AppHarness):
connection_banner.backend_thread.join()
# Error modal should now be displayed
- connection_banner._poll_for(lambda: has_error_modal(driver))
+ assert connection_banner._poll_for(lambda: has_error_modal(driver))
+
+ # Increment the counter with backend down
+ increment_button.click()
+ assert connection_banner.poll_for_value(counter_element, exp_not_equal="0") == "1"
# Bring the backend back up
connection_banner._start_backend(port=backend_port)
+ # Create a new StateManager to avoid async loop affinity issues w/ redis
+ await connection_banner._reset_backend_state_manager()
+
# Banner should be gone now
- connection_banner._poll_for(lambda: not has_error_modal(driver))
+ assert connection_banner._poll_for(lambda: not has_error_modal(driver))
+
+ # Count should have incremented after coming back up
+ assert connection_banner.poll_for_value(counter_element, exp_not_equal="1") == "2"
diff --git a/tests/integration/test_deploy_url.py b/tests/integration/test_deploy_url.py
new file mode 100644
index 000000000..f93e9db27
--- /dev/null
+++ b/tests/integration/test_deploy_url.py
@@ -0,0 +1,99 @@
+"""Integration tests for deploy_url."""
+
+from __future__ import annotations
+
+from typing import Generator
+
+import pytest
+from selenium.webdriver.common.by import By
+from selenium.webdriver.remote.webdriver import WebDriver
+from selenium.webdriver.support.ui import WebDriverWait
+
+from reflex.testing import AppHarness
+
+
+def DeployUrlSample() -> None:
+ """Sample app for testing config deploy_url is correct (in tests)."""
+ import reflex as rx
+
+ class State(rx.State):
+ @rx.event
+ def goto_self(self):
+ return rx.redirect(rx.config.get_config().deploy_url) # type: ignore
+
+ def index():
+ return rx.fragment(
+ rx.button("GOTO SELF", on_click=State.goto_self, id="goto_self")
+ )
+
+ app = rx.App(state=rx.State)
+ app.add_page(index)
+
+
+@pytest.fixture(scope="module")
+def deploy_url_sample(
+ tmp_path_factory: pytest.TempPathFactory,
+) -> Generator[AppHarness, None, None]:
+ """AppHarness fixture for testing deploy_url.
+
+ Args:
+ tmp_path_factory: pytest fixture for creating temporary directories.
+
+ Yields:
+ AppHarness: An AppHarness instance.
+ """
+ with AppHarness.create(
+ root=tmp_path_factory.mktemp("deploy_url_sample"),
+ app_source=DeployUrlSample, # type: ignore
+ ) as harness:
+ yield harness
+
+
+@pytest.fixture()
+def driver(deploy_url_sample: AppHarness) -> Generator[WebDriver, None, None]:
+ """WebDriver fixture for testing deploy_url.
+
+ Args:
+ deploy_url_sample: AppHarness fixture for testing deploy_url.
+
+ Yields:
+ WebDriver: A WebDriver instance.
+ """
+ assert deploy_url_sample.app_instance is not None, "app is not running"
+ driver = deploy_url_sample.frontend()
+ try:
+ yield driver
+ finally:
+ driver.quit()
+
+
+def test_deploy_url(deploy_url_sample: AppHarness, driver: WebDriver) -> None:
+ """Test deploy_url is correct.
+
+ Args:
+ deploy_url_sample: AppHarness fixture for testing deploy_url.
+ driver: WebDriver fixture for testing deploy_url.
+ """
+ import reflex as rx
+
+ deploy_url = rx.config.get_config().deploy_url
+ assert deploy_url is not None
+ assert deploy_url != "http://localhost:3000"
+ assert deploy_url == deploy_url_sample.frontend_url
+ driver.get(deploy_url)
+ assert driver.current_url == deploy_url + "/"
+
+
+def test_deploy_url_in_app(deploy_url_sample: AppHarness, driver: WebDriver) -> None:
+ """Test deploy_url is correct in app.
+
+ Args:
+ deploy_url_sample: AppHarness fixture for testing deploy_url.
+ driver: WebDriver fixture for testing deploy_url.
+ """
+ driver.implicitly_wait(10)
+ driver.find_element(By.ID, "goto_self").click()
+
+ WebDriverWait(driver, 10).until(
+ lambda driver: driver.current_url == f"{deploy_url_sample.frontend_url}/"
+ )
diff --git a/tests/integration/test_dynamic_components.py b/tests/integration/test_dynamic_components.py
new file mode 100644
index 000000000..aeebd10e9
--- /dev/null
+++ b/tests/integration/test_dynamic_components.py
@@ -0,0 +1,169 @@
+"""Integration tests for var operations."""
+
+import time
+from typing import Callable, Generator, TypeVar
+
+import pytest
+from selenium.webdriver.common.by import By
+
+from reflex.testing import AppHarness
+
+# pyright: reportOptionalMemberAccess=false, reportGeneralTypeIssues=false, reportUnknownMemberType=false
+
+
+def DynamicComponents():
+ """App with var operations."""
+ import reflex as rx
+
+ class DynamicComponentsState(rx.State):
+ value: int = 10
+
+ button: rx.Component = rx.button(
+ "Click me",
+ custom_attrs={
+ "id": "button",
+ },
+ )
+
+ def got_clicked(self):
+ self.button = rx.button(
+ "Clicked",
+ custom_attrs={
+ "id": "button",
+ },
+ )
+
+ @rx.var
+ def client_token_component(self) -> rx.Component:
+ return rx.vstack(
+ rx.el.input(
+ custom_attrs={
+ "id": "token",
+ },
+ value=self.router.session.client_token,
+ is_read_only=True,
+ ),
+ rx.button(
+ "Update",
+ custom_attrs={
+ "id": "update",
+ },
+ on_click=DynamicComponentsState.got_clicked,
+ ),
+ )
+
+ app = rx.App()
+
+ def factorial(n: int) -> int:
+ if n == 0:
+ return 1
+ return n * factorial(n - 1)
+
+ @app.add_page
+ def index():
+ return rx.vstack(
+ DynamicComponentsState.client_token_component,
+ DynamicComponentsState.button,
+ rx.text(
+ DynamicComponentsState._evaluate(
+ lambda state: factorial(state.value), of_type=int
+ ),
+ id="factorial",
+ ),
+ )
+
+
+@pytest.fixture(scope="module")
+def dynamic_components(tmp_path_factory) -> Generator[AppHarness, None, None]:
+ """Start VarOperations app at tmp_path via AppHarness.
+
+ Args:
+ tmp_path_factory: pytest tmp_path_factory fixture
+
+ Yields:
+ running AppHarness instance
+ """
+ with AppHarness.create(
+ root=tmp_path_factory.mktemp("dynamic_components"),
+ app_source=DynamicComponents, # type: ignore
+ ) as harness:
+ assert harness.app_instance is not None, "app is not running"
+ yield harness
+
+
+T = TypeVar("T")
+
+
+def poll_for_result(
+ f: Callable[[], T], exception=Exception, max_attempts=5, seconds_between_attempts=1
+) -> T:
+ """Poll for a result from a function.
+
+ Args:
+ f: function to call
+ exception: exception to catch
+ max_attempts: maximum number of attempts
+ seconds_between_attempts: seconds to wait between
+
+ Returns:
+ Result of the function
+
+ Raises:
+ AssertionError: if the function does not return a value
+ """
+ attempts = 0
+ while attempts < max_attempts:
+ try:
+ return f()
+ except exception:
+ attempts += 1
+ time.sleep(seconds_between_attempts)
+ raise AssertionError("Function did not return a value")
+
+
+@pytest.fixture
+def driver(dynamic_components: AppHarness):
+ """Get an instance of the browser open to the dynamic components app.
+
+ Args:
+ dynamic_components: AppHarness for the dynamic components
+
+ Yields:
+ WebDriver instance.
+ """
+ driver = dynamic_components.frontend()
+ try:
+ token_input = poll_for_result(lambda: driver.find_element(By.ID, "token"))
+ assert token_input
+ # wait for the backend connection to send the token
+ token = dynamic_components.poll_for_value(token_input)
+ assert token is not None
+
+ yield driver
+ finally:
+ driver.quit()
+
+
+def test_dynamic_components(driver, dynamic_components: AppHarness):
+ """Test that the var operations produce the right results.
+
+ Args:
+ driver: selenium WebDriver open to the app
+ dynamic_components: AppHarness for the dynamic components
+ """
+ button = poll_for_result(lambda: driver.find_element(By.ID, "button"))
+ assert button
+ assert button.text == "Click me"
+
+ update_button = driver.find_element(By.ID, "update")
+ assert update_button
+ update_button.click()
+
+ assert (
+ dynamic_components.poll_for_content(button, exp_not_equal="Click me")
+ == "Clicked"
+ )
+
+ factorial = poll_for_result(lambda: driver.find_element(By.ID, "factorial"))
+ assert factorial
+ assert factorial.text == "3628800"
diff --git a/integration/test_dynamic_routes.py b/tests/integration/test_dynamic_routes.py
similarity index 64%
rename from integration/test_dynamic_routes.py
rename to tests/integration/test_dynamic_routes.py
index dd1818eda..31b7fa419 100644
--- a/integration/test_dynamic_routes.py
+++ b/tests/integration/test_dynamic_routes.py
@@ -1,4 +1,5 @@
"""Integration tests for dynamic route page behavior."""
+
from __future__ import annotations
from typing import Callable, Coroutine, Generator, Type
@@ -20,14 +21,17 @@ def DynamicRoute():
class DynamicState(rx.State):
order: List[str] = []
- page_id: str = ""
def on_load(self):
- self.order.append(f"{self.router.page.path}-{self.page_id or 'no page id'}")
+ page_data = f"{self.router.page.path}-{self.page_id or 'no page id'}"
+ print(f"on_load: {page_data}")
+ self.order.append(page_data)
def on_load_redir(self):
query_params = self.router.page.params
- self.order.append(f"on_load_redir-{query_params}")
+ page_data = f"on_load_redir-{query_params}"
+ print(f"on_load_redir: {page_data}")
+ self.order.append(page_data)
return rx.redirect(f"/page/{query_params['page_id']}")
@rx.var
@@ -39,17 +43,15 @@ def DynamicRoute():
def index():
return rx.fragment(
- rx.chakra.input(
+ rx.input(
value=DynamicState.router.session.client_token,
- is_read_only=True,
+ read_only=True,
id="token",
),
- rx.chakra.input(
- value=DynamicState.page_id, is_read_only=True, id="page_id"
- ),
- rx.chakra.input(
+ rx.input(value=rx.State.page_id, read_only=True, id="page_id"), # type: ignore
+ rx.input(
value=DynamicState.router.page.raw_path,
- is_read_only=True,
+ read_only=True,
id="raw_path",
),
rx.link("index", href="/", id="link_index"),
@@ -60,22 +62,80 @@ def DynamicRoute():
id="link_page_next", # type: ignore
),
rx.link("missing", href="/missing", id="link_missing"),
- rx.chakra.list(
+ rx.list( # type: ignore
rx.foreach(
DynamicState.order, # type: ignore
- lambda i: rx.chakra.list_item(rx.text(i)),
+ lambda i: rx.list_item(rx.text(i)),
),
),
)
+ class ArgState(rx.State):
+ """The app state."""
+
+ @rx.var
+ def arg(self) -> int:
+ return int(self.arg_str or 0)
+
+ class ArgSubState(ArgState):
+ @rx.var(cache=True)
+ def cached_arg(self) -> int:
+ return self.arg
+
+ @rx.var(cache=True)
+ def cached_arg_str(self) -> str:
+ return self.arg_str
+
+ @rx.page(route="/arg/[arg_str]")
+ def arg() -> rx.Component:
+ return rx.vstack(
+ rx.data_list.root(
+ rx.data_list.item(
+ rx.data_list.label("rx.State.arg_str (dynamic)"),
+ rx.data_list.value(rx.State.arg_str, id="state-arg_str"), # type: ignore
+ ),
+ rx.data_list.item(
+ rx.data_list.label("ArgState.arg_str (dynamic) (inherited)"),
+ rx.data_list.value(ArgState.arg_str, id="argstate-arg_str"), # type: ignore
+ ),
+ rx.data_list.item(
+ rx.data_list.label("ArgState.arg"),
+ rx.data_list.value(ArgState.arg, id="argstate-arg"),
+ ),
+ rx.data_list.item(
+ rx.data_list.label("ArgSubState.arg_str (dynamic) (inherited)"),
+ rx.data_list.value(ArgSubState.arg_str, id="argsubstate-arg_str"), # type: ignore
+ ),
+ rx.data_list.item(
+ rx.data_list.label("ArgSubState.arg (inherited)"),
+ rx.data_list.value(ArgSubState.arg, id="argsubstate-arg"),
+ ),
+ rx.data_list.item(
+ rx.data_list.label("ArgSubState.cached_arg"),
+ rx.data_list.value(
+ ArgSubState.cached_arg, id="argsubstate-cached_arg"
+ ),
+ ),
+ rx.data_list.item(
+ rx.data_list.label("ArgSubState.cached_arg_str"),
+ rx.data_list.value(
+ ArgSubState.cached_arg_str, id="argsubstate-cached_arg_str"
+ ),
+ ),
+ ),
+ rx.link("+", href=f"/arg/{ArgState.arg + 1}", id="next-page"),
+ align="center",
+ height="100vh",
+ )
+
@rx.page(route="/redirect-page/[page_id]", on_load=DynamicState.on_load_redir) # type: ignore
def redirect_page():
return rx.fragment(rx.text("redirecting..."))
app = rx.App(state=rx.State)
- app.add_page(index)
app.add_page(index, route="/page/[page_id]", on_load=DynamicState.on_load) # type: ignore
app.add_page(index, route="/static/x", on_load=DynamicState.on_load) # type: ignore
+ app.add_page(index)
app.add_custom_404_page(on_load=DynamicState.on_load) # type: ignore
@@ -153,18 +213,23 @@ def poll_for_order(
Returns:
An async function that polls for the order list to match the expected order.
"""
+ dynamic_state_name = dynamic_route.get_state_name("_dynamic_state")
+ dynamic_state_full_name = dynamic_route.get_full_state_name(["_dynamic_state"])
async def _poll_for_order(exp_order: list[str]):
async def _backend_state():
- return await dynamic_route.get_state(f"{token}_state.dynamic_state")
+ return await dynamic_route.get_state(f"{token}_{dynamic_state_full_name}")
async def _check():
return (await _backend_state()).substates[
- "dynamic_state"
+ dynamic_state_name
].order == exp_order
- await AppHarness._poll_for_async(_check)
- assert (await _backend_state()).substates["dynamic_state"].order == exp_order
+ await AppHarness._poll_for_async(_check, timeout=60)
+ assert (
+ list((await _backend_state()).substates[dynamic_state_name].order)
+ == exp_order
+ )
return _poll_for_order
@@ -184,6 +249,7 @@ async def test_on_load_navigate(
token: The token visible in the driver browser.
poll_for_order: function that polls for the order list to match the expected order.
"""
+ dynamic_state_full_name = dynamic_route.get_full_state_name(["_dynamic_state"])
assert dynamic_route.app_instance is not None
is_prod = isinstance(dynamic_route, AppHarnessProd)
link = driver.find_element(By.ID, "link_page_next")
@@ -233,7 +299,7 @@ async def test_on_load_navigate(
driver.get(f"{driver.current_url}?foo=bar")
await poll_for_order(exp_order)
assert (
- await dynamic_route.get_state(f"{token}_state.dynamic_state")
+ await dynamic_route.get_state(f"{token}_{dynamic_state_full_name}")
).router.page.params["foo"] == "bar"
# hit a 404 and ensure we still hydrate
@@ -301,3 +367,50 @@ async def test_on_load_navigate_non_dynamic(
link.click()
assert urlsplit(driver.current_url).path == "/static/x/"
await poll_for_order(["/static/x-no page id", "/static/x-no page id"])
+
+
+@pytest.mark.asyncio
+async def test_render_dynamic_arg(
+ dynamic_route: AppHarness,
+ driver: WebDriver,
+):
+ """Assert that dynamic arg var is rendered correctly in different contexts.
+
+ Args:
+ dynamic_route: harness for DynamicRoute app.
+ driver: WebDriver instance.
+ """
+ assert dynamic_route.app_instance is not None
+ with poll_for_navigation(driver):
+ driver.get(f"{dynamic_route.frontend_url}/arg/0")
+
+ def assert_content(expected: str, expect_not: str):
+ ids = [
+ "state-arg_str",
+ "argstate-arg",
+ "argstate-arg_str",
+ "argsubstate-arg_str",
+ "argsubstate-arg",
+ "argsubstate-cached_arg",
+ "argsubstate-cached_arg_str",
+ ]
+ for id in ids:
+ el = driver.find_element(By.ID, id)
+ assert el
+ assert (
+ dynamic_route.poll_for_content(el, exp_not_equal=expect_not) == expected
+ )
+
+ assert_content("0", "")
+ next_page_link = driver.find_element(By.ID, "next-page")
+ assert next_page_link
+ with poll_for_navigation(driver):
+ next_page_link.click()
+ assert driver.current_url == f"{dynamic_route.frontend_url}/arg/1/"
+ assert_content("1", "0")
+ next_page_link = driver.find_element(By.ID, "next-page")
+ assert next_page_link
+ with poll_for_navigation(driver):
+ next_page_link.click()
+ assert driver.current_url == f"{dynamic_route.frontend_url}/arg/2/"
+ assert_content("2", "1")
diff --git a/integration/test_event_actions.py b/tests/integration/test_event_actions.py
similarity index 95%
rename from integration/test_event_actions.py
rename to tests/integration/test_event_actions.py
index 3991704b8..5d278835e 100644
--- a/integration/test_event_actions.py
+++ b/tests/integration/test_event_actions.py
@@ -1,4 +1,5 @@
"""Ensure stopPropagation and preventDefault work as expected."""
+
from __future__ import annotations
import asyncio
@@ -23,6 +24,7 @@ def TestEventAction():
def on_click(self, ev):
self.order.append(f"on_click:{ev}")
+ @rx.event
def on_click2(self):
self.order.append("on_click2")
@@ -52,7 +54,7 @@ def TestEventAction():
def index():
return rx.vstack(
- rx.chakra.input(
+ rx.input(
value=EventActionState.router.session.client_token,
is_read_only=True,
id="token",
@@ -145,10 +147,10 @@ def TestEventAction():
200
).stop_propagation,
),
- rx.chakra.list(
+ rx.list( # type: ignore
rx.foreach(
EventActionState.order, # type: ignore
- rx.chakra.list_item,
+ rx.list_item,
),
),
on_click=EventActionState.on_click("outer"), # type: ignore
@@ -228,20 +230,18 @@ def poll_for_order(
Returns:
An async function that polls for the order list to match the expected order.
"""
+ state_name = event_action.get_state_name("_event_action_state")
+ state_full_name = event_action.get_full_state_name(["_event_action_state"])
async def _poll_for_order(exp_order: list[str]):
async def _backend_state():
- return await event_action.get_state(f"{token}_state.event_action_state")
+ return await event_action.get_state(f"{token}_{state_full_name}")
async def _check():
- return (await _backend_state()).substates[
- "event_action_state"
- ].order == exp_order
+ return (await _backend_state()).substates[state_name].order == exp_order
await AppHarness._poll_for_async(_check)
- assert (await _backend_state()).substates[
- "event_action_state"
- ].order == exp_order
+ assert (await _backend_state()).substates[state_name].order == exp_order
return _poll_for_order
diff --git a/integration/test_event_chain.py b/tests/integration/test_event_chain.py
similarity index 94%
rename from integration/test_event_chain.py
rename to tests/integration/test_event_chain.py
index fe3eaf2a8..ea2d2191c 100644
--- a/integration/test_event_chain.py
+++ b/tests/integration/test_event_chain.py
@@ -1,4 +1,5 @@
"""Ensure that Event Chains are properly queued and handled between frontend and backend."""
+
from __future__ import annotations
from typing import Generator
@@ -26,45 +27,55 @@ def EventChain():
event_order: List[str] = []
interim_value: str = ""
+ @rx.event
def event_no_args(self):
self.event_order.append("event_no_args")
+ @rx.event
def event_arg(self, arg):
self.event_order.append(f"event_arg:{arg}")
+ @rx.event
def event_arg_repr_type(self, arg):
self.event_order.append(f"event_arg_repr:{arg!r}_{type(arg).__name__}")
+ @rx.event
def event_nested_1(self):
self.event_order.append("event_nested_1")
yield State.event_nested_2
yield State.event_arg("nested_1") # type: ignore
+ @rx.event
def event_nested_2(self):
self.event_order.append("event_nested_2")
yield State.event_nested_3
yield rx.console_log("event_nested_2")
yield State.event_arg("nested_2") # type: ignore
+ @rx.event
def event_nested_3(self):
self.event_order.append("event_nested_3")
yield State.event_no_args
yield State.event_arg("nested_3") # type: ignore
+ @rx.event
def on_load_return_chain(self):
self.event_order.append("on_load_return_chain")
return [State.event_arg(1), State.event_arg(2), State.event_arg(3)] # type: ignore
+ @rx.event
def on_load_yield_chain(self):
self.event_order.append("on_load_yield_chain")
yield State.event_arg(4) # type: ignore
yield State.event_arg(5) # type: ignore
yield State.event_arg(6) # type: ignore
+ @rx.event
def click_return_event(self):
self.event_order.append("click_return_event")
return State.event_no_args
+ @rx.event
def click_return_events(self):
self.event_order.append("click_return_events")
return [
@@ -74,6 +85,7 @@ def EventChain():
State.event_arg(9), # type: ignore
]
+ @rx.event
def click_yield_chain(self):
self.event_order.append("click_yield_chain:0")
yield State.event_arg(10) # type: ignore
@@ -84,6 +96,7 @@ def EventChain():
yield State.event_arg(12) # type: ignore
self.event_order.append("click_yield_chain:3")
+ @rx.event
def click_yield_many_events(self):
self.event_order.append("click_yield_many_events")
for ix in range(MANY_EVENTS):
@@ -91,33 +104,40 @@ def EventChain():
yield rx.console_log(f"many_events_{ix}")
self.event_order.append("click_yield_many_events_done")
+ @rx.event
def click_yield_nested(self):
self.event_order.append("click_yield_nested")
yield State.event_nested_1
yield State.event_arg("yield_nested") # type: ignore
+ @rx.event
def redirect_return_chain(self):
self.event_order.append("redirect_return_chain")
yield rx.redirect("/on-load-return-chain")
+ @rx.event
def redirect_yield_chain(self):
self.event_order.append("redirect_yield_chain")
yield rx.redirect("/on-load-yield-chain")
+ @rx.event
def click_return_int_type(self):
self.event_order.append("click_return_int_type")
return State.event_arg_repr_type(1) # type: ignore
+ @rx.event
def click_return_dict_type(self):
self.event_order.append("click_return_dict_type")
return State.event_arg_repr_type({"a": 1}) # type: ignore
+ @rx.event
async def click_yield_interim_value_async(self):
self.interim_value = "interim"
yield
await asyncio.sleep(0.5)
self.interim_value = "final"
+ @rx.event
def click_yield_interim_value(self):
self.interim_value = "interim"
yield
@@ -126,7 +146,7 @@ def EventChain():
app = rx.App(state=rx.State)
- token_input = rx.chakra.input(
+ token_input = rx.input(
value=State.router.session.client_token, is_read_only=True, id="token"
)
@@ -134,9 +154,7 @@ def EventChain():
def index():
return rx.fragment(
token_input,
- rx.chakra.input(
- value=State.interim_value, is_read_only=True, id="interim_value"
- ),
+ rx.input(value=State.interim_value, is_read_only=True, id="interim_value"),
rx.button(
"Return Event",
id="return_event",
@@ -300,7 +318,8 @@ def assert_token(event_chain: AppHarness, driver: WebDriver) -> str:
token = event_chain.poll_for_value(token_input)
assert token is not None
- return f"{token}_state.state"
+ state_name = event_chain.get_full_state_name(["_state"])
+ return f"{token}_{state_name}"
@pytest.mark.parametrize(
@@ -399,16 +418,17 @@ async def test_event_chain_click(
exp_event_order: the expected events recorded in the State
"""
token = assert_token(event_chain, driver)
+ state_name = event_chain.get_state_name("_state")
btn = driver.find_element(By.ID, button_id)
btn.click()
async def _has_all_events():
return len(
- (await event_chain.get_state(token)).substates["state"].event_order
+ (await event_chain.get_state(token)).substates[state_name].event_order
) == len(exp_event_order)
await AppHarness._poll_for_async(_has_all_events)
- event_order = (await event_chain.get_state(token)).substates["state"].event_order
+ event_order = (await event_chain.get_state(token)).substates[state_name].event_order
assert event_order == exp_event_order
@@ -453,14 +473,15 @@ async def test_event_chain_on_load(
assert event_chain.frontend_url is not None
driver.get(event_chain.frontend_url + uri)
token = assert_token(event_chain, driver)
+ state_name = event_chain.get_state_name("_state")
async def _has_all_events():
return len(
- (await event_chain.get_state(token)).substates["state"].event_order
+ (await event_chain.get_state(token)).substates[state_name].event_order
) == len(exp_event_order)
await AppHarness._poll_for_async(_has_all_events)
- backend_state = (await event_chain.get_state(token)).substates["state"]
+ backend_state = (await event_chain.get_state(token)).substates[state_name]
assert backend_state.event_order == exp_event_order
assert backend_state.is_hydrated is True
@@ -525,6 +546,7 @@ async def test_event_chain_on_mount(
assert event_chain.frontend_url is not None
driver.get(event_chain.frontend_url + uri)
token = assert_token(event_chain, driver)
+ state_name = event_chain.get_state_name("_state")
unmount_button = driver.find_element(By.ID, "unmount")
assert unmount_button
@@ -532,11 +554,11 @@ async def test_event_chain_on_mount(
async def _has_all_events():
return len(
- (await event_chain.get_state(token)).substates["state"].event_order
+ (await event_chain.get_state(token)).substates[state_name].event_order
) == len(exp_event_order)
await AppHarness._poll_for_async(_has_all_events)
- event_order = (await event_chain.get_state(token)).substates["state"].event_order
+ event_order = (await event_chain.get_state(token)).substates[state_name].event_order
assert event_order == exp_event_order
diff --git a/tests/integration/test_exception_handlers.py b/tests/integration/test_exception_handlers.py
new file mode 100644
index 000000000..00683c48b
--- /dev/null
+++ b/tests/integration/test_exception_handlers.py
@@ -0,0 +1,154 @@
+"""Integration tests for event exception handlers."""
+
+from __future__ import annotations
+
+import time
+from typing import Generator, Type
+
+import pytest
+from selenium.webdriver.common.by import By
+from selenium.webdriver.remote.webdriver import WebDriver
+from selenium.webdriver.support import expected_conditions as EC
+from selenium.webdriver.support.ui import WebDriverWait
+
+from reflex.testing import AppHarness
+
+
+def TestApp():
+ """A test app for event exception handler integration."""
+ import reflex as rx
+
+ class TestAppConfig(rx.Config):
+ """Config for the TestApp app."""
+
+ pass
+
+ class TestAppState(rx.State):
+ """State for the TestApp app."""
+
+ def divide_by_number(self, number: int):
+ """Divide by number and print the result.
+
+ Args:
+ number: number to divide by
+
+ """
+ print(1 / number)
+
+ app = rx.App(state=rx.State)
+
+ @app.add_page
+ def index():
+ return rx.vstack(
+ rx.button(
+ "induce_frontend_error",
+ on_click=rx.call_script("induce_frontend_error()"),
+ id="induce-frontend-error-btn",
+ ),
+ rx.button(
+ "induce_backend_error",
+ on_click=lambda: TestAppState.divide_by_number(0), # type: ignore
+ id="induce-backend-error-btn",
+ ),
+ )
+
+
+@pytest.fixture(scope="module")
+def test_app(
+ app_harness_env: Type[AppHarness], tmp_path_factory
+) -> Generator[AppHarness, None, None]:
+ """Start TestApp app at tmp_path via AppHarness.
+
+ Args:
+ app_harness_env: either AppHarness (dev) or AppHarnessProd (prod)
+ tmp_path_factory: pytest tmp_path_factory fixture
+
+ Yields:
+ running AppHarness instance
+
+ """
+ with app_harness_env.create(
+ root=tmp_path_factory.mktemp("test_app"),
+ app_name=f"testapp_{app_harness_env.__name__.lower()}",
+ app_source=TestApp, # type: ignore
+ ) as harness:
+ yield harness
+
+
+@pytest.fixture
+def driver(test_app: AppHarness) -> Generator[WebDriver, None, None]:
+ """Get an instance of the browser open to the test_app app.
+
+ Args:
+ test_app: harness for TestApp app
+
+ Yields:
+ WebDriver instance.
+
+ """
+ assert test_app.app_instance is not None, "app is not running"
+ driver = test_app.frontend()
+ try:
+ yield driver
+ finally:
+ driver.quit()
+
+
+def test_frontend_exception_handler_during_runtime(
+ driver: WebDriver,
+ capsys,
+):
+ """Test calling frontend exception handler during runtime.
+
+ We send an event containing a call to a non-existent function in the frontend.
+ This should trigger the default frontend exception handler.
+
+ Args:
+ driver: WebDriver instance.
+ capsys: pytest fixture for capturing stdout and stderr.
+
+ """
+ reset_button = WebDriverWait(driver, 20).until(
+ EC.element_to_be_clickable((By.ID, "induce-frontend-error-btn"))
+ )
+
+ reset_button.click()
+
+ # Wait for the error to be logged
+ time.sleep(2)
+
+ captured_default_handler_output = capsys.readouterr()
+ assert (
+ "induce_frontend_error" in captured_default_handler_output.out
+ and "ReferenceError" in captured_default_handler_output.out
+ )
+
+
+def test_backend_exception_handler_during_runtime(
+ driver: WebDriver,
+ capsys,
+):
+ """Test calling backend exception handler during runtime.
+
+ We invoke TestAppState.divide_by_zero to induce backend error.
+ This should trigger the default backend exception handler.
+
+ Args:
+ driver: WebDriver instance.
+ capsys: pytest fixture for capturing stdout and stderr.
+
+ """
+ reset_button = WebDriverWait(driver, 20).until(
+ EC.element_to_be_clickable((By.ID, "induce-backend-error-btn"))
+ )
+
+ reset_button.click()
+
+ # Wait for the error to be logged
+ time.sleep(2)
+
+ captured_default_handler_output = capsys.readouterr()
+ assert (
+ "divide_by_number" in captured_default_handler_output.out
+ and "ZeroDivisionError" in captured_default_handler_output.out
+ )
diff --git a/integration/test_form_submit.py b/tests/integration/test_form_submit.py
similarity index 75%
rename from integration/test_form_submit.py
rename to tests/integration/test_form_submit.py
index f7e2ba47d..3bfcf6e8c 100644
--- a/integration/test_form_submit.py
+++ b/tests/integration/test_form_submit.py
@@ -1,4 +1,5 @@
"""Integration tests for forms."""
+
import functools
import time
from typing import Generator
@@ -34,28 +35,29 @@ def FormSubmit(form_component):
@app.add_page
def index():
return rx.vstack(
- rx.chakra.input(
+ rx.input(
value=FormState.router.session.client_token,
is_read_only=True,
id="token",
),
eval(form_component)(
rx.vstack(
- rx.chakra.input(id="name_input"),
- rx.hstack(rx.chakra.pin_input(length=4, id="pin_input")),
- rx.chakra.number_input(id="number_input"),
+ rx.input(id="name_input"),
rx.checkbox(id="bool_input"),
rx.switch(id="bool_input2"),
rx.checkbox(id="bool_input3"),
rx.switch(id="bool_input4"),
rx.slider(id="slider_input", default_value=[50], width="100%"),
- rx.chakra.range_slider(id="range_input"),
rx.radio(["option1", "option2"], id="radio_input"),
rx.radio(FormState.var_options, id="radio_input_var"),
- rx.chakra.select(["option1", "option2"], id="select_input"),
- rx.chakra.select(FormState.var_options, id="select_input_var"),
+ rx.select(
+ ["option1", "option2"],
+ name="select_input",
+ default_value="option1",
+ ),
+ rx.select(FormState.var_options, id="select_input_var"),
rx.text_area(id="text_area_input"),
- rx.chakra.input(
+ rx.input(
id="debounce_input",
debounce_timeout=0,
on_change=rx.console_log,
@@ -93,22 +95,19 @@ def FormSubmitName(form_component):
@app.add_page
def index():
return rx.vstack(
- rx.chakra.input(
+ rx.input(
value=FormState.router.session.client_token,
is_read_only=True,
id="token",
),
eval(form_component)(
rx.vstack(
- rx.chakra.input(name="name_input"),
- rx.hstack(rx.chakra.pin_input(length=4, name="pin_input")),
- rx.chakra.number_input(name="number_input"),
+ rx.input(name="name_input"),
rx.checkbox(name="bool_input"),
rx.switch(name="bool_input2"),
rx.checkbox(name="bool_input3"),
rx.switch(name="bool_input4"),
rx.slider(name="slider_input", default_value=[50], width="100%"),
- rx.chakra.range_slider(name="range_input"),
rx.radio(FormState.options, name="radio_input"),
rx.select(
FormState.options,
@@ -116,21 +115,13 @@ def FormSubmitName(form_component):
default_value=FormState.options[0],
),
rx.text_area(name="text_area_input"),
- rx.chakra.input_group(
- rx.chakra.input_left_element(rx.icon(tag="chevron_right")),
- rx.chakra.input(
- name="debounce_input",
- debounce_timeout=0,
- on_change=rx.console_log,
- ),
- rx.chakra.input_right_element(rx.icon(tag="chevron_left")),
- ),
- rx.chakra.button_group(
- rx.button("Submit", type_="submit"),
- rx.icon_button(FormState.val, icon=rx.icon(tag="plus")),
- variant="outline",
- is_attached=True,
+ rx.input(
+ name="debounce_input",
+ debounce_timeout=0,
+ on_change=rx.console_log,
),
+ rx.button("Submit", type_="submit"),
+ rx.icon_button(rx.icon(tag="plus")),
),
on_submit=FormState.form_submit,
custom_attrs={"action": "/invalid"},
@@ -147,16 +138,12 @@ def FormSubmitName(form_component):
functools.partial(FormSubmitName, form_component="rx.form.root"),
functools.partial(FormSubmit, form_component="rx.el.form"),
functools.partial(FormSubmitName, form_component="rx.el.form"),
- functools.partial(FormSubmit, form_component="rx.chakra.form"),
- functools.partial(FormSubmitName, form_component="rx.chakra.form"),
],
ids=[
"id-radix",
"name-radix",
"id-html",
"name-html",
- "id-chakra",
- "name-chakra",
],
)
def form_submit(request, tmp_path_factory) -> Generator[AppHarness, None, None]:
@@ -219,16 +206,6 @@ async def test_submit(driver, form_submit: AppHarness):
name_input = driver.find_element(by, "name_input")
name_input.send_keys("foo")
- pin_inputs = driver.find_elements(By.CLASS_NAME, "chakra-pin-input")
- pin_values = ["8", "1", "6", "4"]
- for i, pin_input in enumerate(pin_inputs):
- pin_input.send_keys(pin_values[i])
-
- number_input = driver.find_element(By.CLASS_NAME, "chakra-numberinput")
- buttons = number_input.find_elements(By.XPATH, "//div[@role='button']")
- for _ in range(3):
- buttons[1].click()
-
checkbox_input = driver.find_element(By.XPATH, "//button[@role='checkbox']")
checkbox_input.click()
@@ -251,10 +228,13 @@ async def test_submit(driver, form_submit: AppHarness):
submit_input = driver.find_element(By.CLASS_NAME, "rt-Button")
submit_input.click()
+ state_name = form_submit.get_state_name("_form_state")
+ full_state_name = form_submit.get_full_state_name(["_form_state"])
+
async def get_form_data():
return (
- (await form_submit.get_state(f"{token}_state.form_state"))
- .substates["form_state"]
+ (await form_submit.get_state(f"{token}_{full_state_name}"))
+ .substates[state_name]
.form_data
)
@@ -264,16 +244,15 @@ async def test_submit(driver, form_submit: AppHarness):
form_data = format.collect_form_dict_names(form_data)
+ print(form_data)
+
assert form_data["name_input"] == "foo"
- assert form_data["pin_input"] == pin_values
- assert form_data["number_input"] == "-3"
assert form_data["bool_input"]
assert form_data["bool_input2"]
assert not form_data.get("bool_input3", False)
assert not form_data.get("bool_input4", False)
assert form_data["slider_input"] == "50"
- assert form_data["range_input"] == ["25", "75"]
assert form_data["radio_input"] == "option2"
assert form_data["select_input"] == "option1"
assert form_data["text_area_input"] == "Some\nText"
diff --git a/integration/test_input.py b/tests/integration/test_input.py
similarity index 94%
rename from integration/test_input.py
rename to tests/integration/test_input.py
index a57219b97..4679104a4 100644
--- a/integration/test_input.py
+++ b/tests/integration/test_input.py
@@ -1,4 +1,5 @@
"""Integration tests for text input and related components."""
+
from typing import Generator
import pytest
@@ -85,9 +86,12 @@ async def test_fully_controlled_input(fully_controlled_input: AppHarness):
token = fully_controlled_input.poll_for_value(token_input)
assert token
+ state_name = fully_controlled_input.get_state_name("_state")
+ full_state_name = fully_controlled_input.get_full_state_name(["_state"])
+
async def get_state_text():
- state = await fully_controlled_input.get_state(f"{token}_state.state")
- return state.substates["state"].text
+ state = await fully_controlled_input.get_state(f"{token}_{full_state_name}")
+ return state.substates[state_name].text
# ensure defaults are set correctly
assert (
@@ -137,8 +141,10 @@ async def test_fully_controlled_input(fully_controlled_input: AppHarness):
assert fully_controlled_input.poll_for_value(plain_value_input) == "ifoonitial"
# clear the input on the backend
- async with fully_controlled_input.modify_state(f"{token}_state.state") as state:
- state.substates["state"].text = ""
+ async with fully_controlled_input.modify_state(
+ f"{token}_{full_state_name}"
+ ) as state:
+ state.substates[state_name].text = ""
assert await get_state_text() == ""
assert (
fully_controlled_input.poll_for_value(
diff --git a/integration/test_large_state.py b/tests/integration/test_large_state.py
similarity index 99%
rename from integration/test_large_state.py
rename to tests/integration/test_large_state.py
index 250b751a8..23a534a2b 100644
--- a/integration/test_large_state.py
+++ b/tests/integration/test_large_state.py
@@ -1,4 +1,5 @@
"""Test large state."""
+
import time
import jinja2
diff --git a/tests/integration/test_lifespan.py b/tests/integration/test_lifespan.py
new file mode 100644
index 000000000..22c399c07
--- /dev/null
+++ b/tests/integration/test_lifespan.py
@@ -0,0 +1,122 @@
+"""Test cases for the FastAPI lifespan integration."""
+
+from typing import Generator
+
+import pytest
+from selenium.webdriver.common.by import By
+
+from reflex.testing import AppHarness
+
+from .utils import SessionStorage
+
+
+def LifespanApp():
+ """App with lifespan tasks and context."""
+ import asyncio
+ from contextlib import asynccontextmanager
+
+ import reflex as rx
+
+ lifespan_task_global = 0
+ lifespan_context_global = 0
+
+ @asynccontextmanager
+ async def lifespan_context(app, inc: int = 1):
+ global lifespan_context_global
+ print(f"Lifespan context entered: {app}.")
+ lifespan_context_global += inc # pyright: ignore[reportUnboundVariable]
+ try:
+ yield
+ finally:
+ print("Lifespan context exited.")
+ lifespan_context_global += inc
+
+ async def lifespan_task(inc: int = 1):
+ global lifespan_task_global
+ print("Lifespan global started.")
+ try:
+ while True:
+ lifespan_task_global += inc # pyright: ignore[reportUnboundVariable]
+ await asyncio.sleep(0.1)
+ except asyncio.CancelledError as ce:
+ print(f"Lifespan global cancelled: {ce}.")
+ lifespan_task_global = 0
+
+ class LifespanState(rx.State):
+ @rx.var
+ def task_global(self) -> int:
+ return lifespan_task_global
+
+ @rx.var
+ def context_global(self) -> int:
+ return lifespan_context_global
+
+ @rx.event
+ def tick(self, date):
+ pass
+
+ def index():
+ return rx.vstack(
+ rx.text(LifespanState.task_global, id="task_global"),
+ rx.text(LifespanState.context_global, id="context_global"),
+ rx.moment(interval=100, on_change=LifespanState.tick),
+ )
+
+ app = rx.App()
+ app.register_lifespan_task(lifespan_task)
+ app.register_lifespan_task(lifespan_context, inc=2)
+ app.add_page(index)
+
+
+@pytest.fixture()
+def lifespan_app(tmp_path) -> Generator[AppHarness, None, None]:
+ """Start LifespanApp app at tmp_path via AppHarness.
+
+ Args:
+ tmp_path: pytest tmp_path fixture
+
+ Yields:
+ running AppHarness instance
+ """
+ with AppHarness.create(
+ root=tmp_path,
+ app_source=LifespanApp, # type: ignore
+ ) as harness:
+ yield harness
+
+
+@pytest.mark.asyncio
+async def test_lifespan(lifespan_app: AppHarness):
+ """Test the lifespan integration.
+
+ Args:
+ lifespan_app: harness for LifespanApp app
+ """
+ assert lifespan_app.app_module is not None, "app module is not found"
+ assert lifespan_app.app_instance is not None, "app is not running"
+ driver = lifespan_app.frontend()
+
+ ss = SessionStorage(driver)
+ assert AppHarness._poll_for(lambda: ss.get("token") is not None), "token not found"
+
+ context_global = driver.find_element(By.ID, "context_global")
+ task_global = driver.find_element(By.ID, "task_global")
+
+ assert context_global.text == "2"
+ assert lifespan_app.app_module.lifespan_context_global == 2 # type: ignore
+
+ original_task_global_text = task_global.text
+ original_task_global_value = int(original_task_global_text)
+ lifespan_app.poll_for_content(task_global, exp_not_equal=original_task_global_text)
+ assert lifespan_app.app_module.lifespan_task_global > original_task_global_value # type: ignore
+ assert int(task_global.text) > original_task_global_value
+
+ # Kill the backend
+ assert lifespan_app.backend is not None
+ lifespan_app.backend.should_exit = True
+ if lifespan_app.backend_thread is not None:
+ lifespan_app.backend_thread.join()
+
+ # Check that the lifespan tasks have been cancelled
+ assert lifespan_app.app_module.lifespan_task_global == 0
+ assert lifespan_app.app_module.lifespan_context_global == 4
diff --git a/integration/test_login_flow.py b/tests/integration/test_login_flow.py
similarity index 94%
rename from integration/test_login_flow.py
rename to tests/integration/test_login_flow.py
index bfa57ed02..ecaade9cf 100644
--- a/integration/test_login_flow.py
+++ b/tests/integration/test_login_flow.py
@@ -1,4 +1,5 @@
"""Integration tests for client side storage."""
+
from __future__ import annotations
from typing import Generator
@@ -20,9 +21,11 @@ def LoginSample():
class State(rx.State):
auth_token: str = rx.LocalStorage("")
+ @rx.event
def logout(self):
self.set_auth_token("")
+ @rx.event
def login(self):
self.set_auth_token("12345")
yield rx.redirect("/")
@@ -136,6 +139,9 @@ def test_login_flow(
logout_button = driver.find_element(By.ID, "logout")
logout_button.click()
- assert login_sample._poll_for(lambda: local_storage["state.state.auth_token"] == "")
+ state_name = login_sample.get_full_state_name(["_state"])
+ assert login_sample._poll_for(
+ lambda: local_storage[f"{state_name}.auth_token"] == ""
+ )
with pytest.raises(NoSuchElementException):
driver.find_element(By.ID, "auth-token")
diff --git a/integration/test_media.py b/tests/integration/test_media.py
similarity index 96%
rename from integration/test_media.py
rename to tests/integration/test_media.py
index 3eb1f2007..c10f7102b 100644
--- a/integration/test_media.py
+++ b/tests/integration/test_media.py
@@ -1,4 +1,5 @@
"""Integration tests for media components."""
+
from typing import Generator
import pytest
@@ -21,31 +22,31 @@ def MediaApp():
img.format = format # type: ignore
return img
- @rx.cached_var
+ @rx.var(cache=True)
def img_default(self) -> Image.Image:
return self._blue()
- @rx.cached_var
+ @rx.var(cache=True)
def img_bmp(self) -> Image.Image:
return self._blue(format="BMP")
- @rx.cached_var
+ @rx.var(cache=True)
def img_jpg(self) -> Image.Image:
return self._blue(format="JPEG")
- @rx.cached_var
+ @rx.var(cache=True)
def img_png(self) -> Image.Image:
return self._blue(format="PNG")
- @rx.cached_var
+ @rx.var(cache=True)
def img_gif(self) -> Image.Image:
return self._blue(format="GIF")
- @rx.cached_var
+ @rx.var(cache=True)
def img_webp(self) -> Image.Image:
return self._blue(format="WEBP")
- @rx.cached_var
+ @rx.var(cache=True)
def img_from_url(self) -> Image.Image:
img_url = "https://picsum.photos/id/1/200/300"
img_resp = httpx.get(img_url, follow_redirects=True)
diff --git a/integration/test_navigation.py b/tests/integration/test_navigation.py
similarity index 96%
rename from integration/test_navigation.py
rename to tests/integration/test_navigation.py
index 2c288552f..492ae4510 100644
--- a/integration/test_navigation.py
+++ b/tests/integration/test_navigation.py
@@ -1,4 +1,5 @@
"""Integration tests for links and related components."""
+
from typing import Generator
from urllib.parse import urlsplit
@@ -67,8 +68,7 @@ async def test_navigation_app(navigation_app: AppHarness):
driver = navigation_app.frontend()
ss = SessionStorage(driver)
- token = AppHarness._poll_for(lambda: ss.get("token") is not None)
- assert token is not None
+ assert AppHarness._poll_for(lambda: ss.get("token") is not None), "token not found"
internal_link = driver.find_element(By.ID, "internal")
diff --git a/integration/test_server_side_event.py b/tests/integration/test_server_side_event.py
similarity index 95%
rename from integration/test_server_side_event.py
rename to tests/integration/test_server_side_event.py
index 067cecfcc..cacf6e1c5 100644
--- a/integration/test_server_side_event.py
+++ b/tests/integration/test_server_side_event.py
@@ -1,4 +1,5 @@
"""Integration tests for special server side events."""
+
import time
from typing import Generator
@@ -13,16 +14,19 @@ def ServerSideEvent():
import reflex as rx
class SSState(rx.State):
+ @rx.event
def set_value_yield(self):
yield rx.set_value("a", "")
yield rx.set_value("b", "")
yield rx.set_value("c", "")
+ @rx.event
def set_value_yield_return(self):
yield rx.set_value("a", "")
yield rx.set_value("b", "")
return rx.set_value("c", "")
+ @rx.event
def set_value_return(self):
return [
rx.set_value("a", ""),
@@ -30,6 +34,7 @@ def ServerSideEvent():
rx.set_value("c", ""),
]
+ @rx.event
def set_value_return_c(self):
return rx.set_value("c", "")
@@ -38,12 +43,12 @@ def ServerSideEvent():
@app.add_page
def index():
return rx.fragment(
- rx.chakra.input(
+ rx.input(
id="token", value=SSState.router.session.client_token, is_read_only=True
),
- rx.chakra.input(default_value="a", id="a"),
- rx.chakra.input(default_value="b", id="b"),
- rx.chakra.input(default_value="c", id="c"),
+ rx.input(default_value="a", id="a"),
+ rx.input(default_value="b", id="b"),
+ rx.input(default_value="c", id="c"),
rx.button(
"Clear Immediate",
id="clear_immediate",
diff --git a/integration/test_shared_state.py b/tests/integration/test_shared_state.py
similarity index 96%
rename from integration/test_shared_state.py
rename to tests/integration/test_shared_state.py
index 363f4536c..6f59c5142 100644
--- a/integration/test_shared_state.py
+++ b/tests/integration/test_shared_state.py
@@ -1,4 +1,5 @@
"""Test shared state."""
+
from __future__ import annotations
from typing import Generator
@@ -11,7 +12,7 @@ from reflex.testing import AppHarness, WebDriver
def SharedStateApp():
"""Test that shared state works as expected."""
import reflex as rx
- from integration.shared.state import SharedState
+ from tests.integration.shared.state import SharedState
class State(SharedState):
pass
diff --git a/integration/test_state_inheritance.py b/tests/integration/test_state_inheritance.py
similarity index 88%
rename from integration/test_state_inheritance.py
rename to tests/integration/test_state_inheritance.py
index 08a7fc951..86ab625e1 100644
--- a/integration/test_state_inheritance.py
+++ b/tests/integration/test_state_inheritance.py
@@ -45,17 +45,15 @@ def StateInheritance():
"""Test that state inheritance works as expected."""
import reflex as rx
- class ChildMixin:
- # mixin basevars only work with pydantic/rx.Base models
- # child_mixin: str = "child_mixin"
+ class ChildMixin(rx.State, mixin=True):
+ child_mixin: str = "child_mixin"
@rx.var
def computed_child_mixin(self) -> str:
return "computed_child_mixin"
- class Mixin(ChildMixin):
- # mixin basevars only work with pydantic/rx.Base models
- # mixin: str = "mixin"
+ class Mixin(ChildMixin, mixin=True):
+ mixin: str = "mixin"
@rx.var
def computed_mixin(self) -> str:
@@ -64,7 +62,7 @@ def StateInheritance():
def on_click_mixin(self):
return rx.call_script("alert('clicked')")
- class OtherMixin(rx.Base):
+ class OtherMixin(rx.State, mixin=True):
other_mixin: str = "other_mixin"
other_mixin_clicks: int = 0
@@ -78,7 +76,7 @@ def StateInheritance():
f"{self.__class__.__name__}.clicked.{self.other_mixin_clicks}"
)
- class Base1(rx.State, Mixin):
+ class Base1(Mixin, rx.State):
_base1: str = "_base1"
base1: str = "base1"
@@ -122,14 +120,15 @@ def StateInheritance():
def index() -> rx.Component:
return rx.vstack(
- rx.chakra.input(
+ rx.input(
id="token", value=Base1.router.session.client_token, is_read_only=True
),
- # Base 1
+ # Base 1 (Mixin, ChildMixin)
rx.heading(Base1.computed_mixin, id="base1-computed_mixin"),
rx.heading(Base1.computed_basevar, id="base1-computed_basevar"),
- rx.heading(Base1.computed_child_mixin, id="base1-child-mixin"),
+ rx.heading(Base1.computed_child_mixin, id="base1-computed-child-mixin"),
rx.heading(Base1.base1, id="base1-base1"),
+ rx.heading(Base1.child_mixin, id="base1-child-mixin"),
rx.button(
"Base1.on_click_mixin",
on_click=Base1.on_click_mixin, # type: ignore
@@ -138,31 +137,33 @@ def StateInheritance():
rx.heading(
Base1.computed_backend_vars_base1, id="base1-computed_backend_vars"
),
- # Base 2
+ # Base 2 (no mixins)
rx.heading(Base2.computed_basevar, id="base2-computed_basevar"),
rx.heading(Base2.base2, id="base2-base2"),
rx.heading(
Base2.computed_backend_vars_base2, id="base2-computed_backend_vars"
),
- # Child 1
+ # Child 1 (Mixin, ChildMixin, OtherMixin)
rx.heading(Child1.computed_basevar, id="child1-computed_basevar"),
rx.heading(Child1.computed_mixin, id="child1-computed_mixin"),
rx.heading(Child1.computed_other_mixin, id="child1-other-mixin"),
- rx.heading(Child1.computed_child_mixin, id="child1-child-mixin"),
+ rx.heading(Child1.computed_child_mixin, id="child1-computed-child-mixin"),
rx.heading(Child1.base1, id="child1-base1"),
rx.heading(Child1.other_mixin, id="child1-other_mixin"),
+ rx.heading(Child1.child_mixin, id="child1-child-mixin"),
rx.button(
"Child1.on_click_other_mixin",
on_click=Child1.on_click_other_mixin, # type: ignore
id="child1-other-mixin-btn",
),
- # Child 2
+ # Child 2 (Mixin, ChildMixin, OtherMixin)
rx.heading(Child2.computed_basevar, id="child2-computed_basevar"),
rx.heading(Child2.computed_mixin, id="child2-computed_mixin"),
rx.heading(Child2.computed_other_mixin, id="child2-other-mixin"),
- rx.heading(Child2.computed_child_mixin, id="child2-child-mixin"),
+ rx.heading(Child2.computed_child_mixin, id="child2-computed-child-mixin"),
rx.heading(Child2.base2, id="child2-base2"),
rx.heading(Child2.other_mixin, id="child2-other_mixin"),
+ rx.heading(Child2.child_mixin, id="child2-child-mixin"),
rx.button(
"Child2.on_click_mixin",
on_click=Child2.on_click_mixin, # type: ignore
@@ -173,15 +174,16 @@ def StateInheritance():
on_click=Child2.on_click_other_mixin, # type: ignore
id="child2-other-mixin-btn",
),
- # Child 3
+ # Child 3 (Mixin, ChildMixin, OtherMixin)
rx.heading(Child3.computed_basevar, id="child3-computed_basevar"),
rx.heading(Child3.computed_mixin, id="child3-computed_mixin"),
rx.heading(Child3.computed_other_mixin, id="child3-other-mixin"),
rx.heading(Child3.computed_childvar, id="child3-computed_childvar"),
- rx.heading(Child3.computed_child_mixin, id="child3-child-mixin"),
+ rx.heading(Child3.computed_child_mixin, id="child3-computed-child-mixin"),
rx.heading(Child3.child3, id="child3-child3"),
rx.heading(Child3.base2, id="child3-base2"),
rx.heading(Child3.other_mixin, id="child3-other_mixin"),
+ rx.heading(Child3.child_mixin, id="child3-child-mixin"),
rx.button(
"Child3.on_click_mixin",
on_click=Child3.on_click_mixin, # type: ignore
@@ -282,7 +284,9 @@ def test_state_inheritance(
base1_computed_basevar = driver.find_element(By.ID, "base1-computed_basevar")
assert base1_computed_basevar.text == "computed_basevar1"
- base1_computed_child_mixin = driver.find_element(By.ID, "base1-child-mixin")
+ base1_computed_child_mixin = driver.find_element(
+ By.ID, "base1-computed-child-mixin"
+ )
assert base1_computed_child_mixin.text == "computed_child_mixin"
base1_base1 = driver.find_element(By.ID, "base1-base1")
@@ -293,6 +297,9 @@ def test_state_inheritance(
)
assert base1_computed_backend_vars.text == "_base1"
+ base1_child_mixin = driver.find_element(By.ID, "base1-child-mixin")
+ assert base1_child_mixin.text == "child_mixin"
+
# Base 2
base2_computed_basevar = driver.find_element(By.ID, "base2-computed_basevar")
assert base2_computed_basevar.text == "computed_basevar2"
@@ -315,7 +322,9 @@ def test_state_inheritance(
child1_computed_other_mixin = driver.find_element(By.ID, "child1-other-mixin")
assert child1_computed_other_mixin.text == "other_mixin"
- child1_computed_child_mixin = driver.find_element(By.ID, "child1-child-mixin")
+ child1_computed_child_mixin = driver.find_element(
+ By.ID, "child1-computed-child-mixin"
+ )
assert child1_computed_child_mixin.text == "computed_child_mixin"
child1_base1 = driver.find_element(By.ID, "child1-base1")
@@ -324,6 +333,9 @@ def test_state_inheritance(
child1_other_mixin = driver.find_element(By.ID, "child1-other_mixin")
assert child1_other_mixin.text == "other_mixin"
+ child1_child_mixin = driver.find_element(By.ID, "child1-child-mixin")
+ assert child1_child_mixin.text == "child_mixin"
+
# Child 2
child2_computed_basevar = driver.find_element(By.ID, "child2-computed_basevar")
assert child2_computed_basevar.text == "computed_basevar2"
@@ -334,7 +346,9 @@ def test_state_inheritance(
child2_computed_other_mixin = driver.find_element(By.ID, "child2-other-mixin")
assert child2_computed_other_mixin.text == "other_mixin"
- child2_computed_child_mixin = driver.find_element(By.ID, "child2-child-mixin")
+ child2_computed_child_mixin = driver.find_element(
+ By.ID, "child2-computed-child-mixin"
+ )
assert child2_computed_child_mixin.text == "computed_child_mixin"
child2_base2 = driver.find_element(By.ID, "child2-base2")
@@ -343,6 +357,9 @@ def test_state_inheritance(
child2_other_mixin = driver.find_element(By.ID, "child2-other_mixin")
assert child2_other_mixin.text == "other_mixin"
+ child2_child_mixin = driver.find_element(By.ID, "child2-child-mixin")
+ assert child2_child_mixin.text == "child_mixin"
+
# Child 3
child3_computed_basevar = driver.find_element(By.ID, "child3-computed_basevar")
assert child3_computed_basevar.text == "computed_basevar2"
@@ -356,7 +373,9 @@ def test_state_inheritance(
child3_computed_childvar = driver.find_element(By.ID, "child3-computed_childvar")
assert child3_computed_childvar.text == "computed_childvar"
- child3_computed_child_mixin = driver.find_element(By.ID, "child3-child-mixin")
+ child3_computed_child_mixin = driver.find_element(
+ By.ID, "child3-computed-child-mixin"
+ )
assert child3_computed_child_mixin.text == "computed_child_mixin"
child3_child3 = driver.find_element(By.ID, "child3-child3")
@@ -368,6 +387,9 @@ def test_state_inheritance(
child3_other_mixin = driver.find_element(By.ID, "child3-other_mixin")
assert child3_other_mixin.text == "other_mixin"
+ child3_child_mixin = driver.find_element(By.ID, "child3-child-mixin")
+ assert child3_child_mixin.text == "child_mixin"
+
child3_computed_backend_vars = driver.find_element(
By.ID, "child3-computed_backend_vars"
)
diff --git a/integration/test_tailwind.py b/tests/integration/test_tailwind.py
similarity index 80%
rename from integration/test_tailwind.py
rename to tests/integration/test_tailwind.py
index ce6bab225..bda664a1c 100644
--- a/integration/test_tailwind.py
+++ b/tests/integration/test_tailwind.py
@@ -25,21 +25,27 @@ def TailwindApp(
paragraph_text: Text for the paragraph.
paragraph_class_name: Tailwind class_name for the paragraph.
"""
+ from pathlib import Path
+
import reflex as rx
- import reflex.components.radix.themes as rdxt
class UnusedState(rx.State):
pass
def index():
return rx.el.div(
- rx.chakra.text(paragraph_text, class_name=paragraph_class_name),
+ rx.text(paragraph_text, class_name=paragraph_class_name),
rx.el.p(paragraph_text, class_name=paragraph_class_name),
- rdxt.text(paragraph_text, as_="p", class_name=paragraph_class_name),
+ rx.text(paragraph_text, as_="p", class_name=paragraph_class_name),
+ rx.el.div("Test external stylesheet", class_name="external"),
id="p-content",
)
- app = rx.App(style={"font_family": "monospace"})
+ assets = Path(__file__).resolve().parent.parent / "assets"
+ assets.mkdir(exist_ok=True)
+ stylesheet = assets / "test_styles.css"
+ stylesheet.write_text(".external { color: rgba(0, 0, 255, 0.5) }")
+ app = rx.App(style={"font_family": "monospace"}, stylesheets=[stylesheet.name])
app.add_page(index)
if tailwind_disabled:
config = rx.config.get_config()
@@ -108,3 +114,9 @@ def test_tailwind_app(tailwind_app: AppHarness, tailwind_disabled: bool):
else:
# expect "text-red-500" from tailwind utility class
assert p.value_of_css_property("color") in TEXT_RED_500_COLOR
+
+ # Assert external stylesheet is applying rules
+ external = driver.find_elements(By.CLASS_NAME, "external")
+ assert len(external) == 1
+ for ext_div in external:
+ assert ext_div.value_of_css_property("color") == "rgba(0, 0, 255, 0.5)"
diff --git a/integration/test_upload.py b/tests/integration/test_upload.py
similarity index 92%
rename from integration/test_upload.py
rename to tests/integration/test_upload.py
index 44fec6b46..813313462 100644
--- a/integration/test_upload.py
+++ b/tests/integration/test_upload.py
@@ -1,4 +1,5 @@
"""Integration tests for file upload."""
+
from __future__ import annotations
import asyncio
@@ -43,7 +44,7 @@ def UploadFile():
def index():
return rx.vstack(
- rx.chakra.input(
+ rx.input(
value=UploadState.router.session.client_token,
is_read_only=True,
id="token",
@@ -173,7 +174,9 @@ async def test_upload_file(
# wait for the backend connection to send the token
token = upload_file.poll_for_value(token_input)
assert token is not None
- substate_token = f"{token}_state.upload_state"
+ full_state_name = upload_file.get_full_state_name(["_upload_state"])
+ state_name = upload_file.get_state_name("_upload_state")
+ substate_token = f"{token}_{full_state_name}"
suffix = "_secondary" if secondary else ""
@@ -196,7 +199,7 @@ async def test_upload_file(
async def get_file_data():
return (
(await upload_file.get_state(substate_token))
- .substates["upload_state"]
+ .substates[state_name]
._file_data
)
@@ -211,8 +214,8 @@ async def test_upload_file(
state = await upload_file.get_state(substate_token)
if secondary:
# only the secondary form tracks progress and chain events
- assert state.substates["upload_state"].event_order.count("upload_progress") == 1
- assert state.substates["upload_state"].event_order.count("chain_event") == 1
+ assert state.substates[state_name].event_order.count("upload_progress") == 1
+ assert state.substates[state_name].event_order.count("chain_event") == 1
@pytest.mark.asyncio
@@ -230,7 +233,9 @@ async def test_upload_file_multiple(tmp_path, upload_file: AppHarness, driver):
# wait for the backend connection to send the token
token = upload_file.poll_for_value(token_input)
assert token is not None
- substate_token = f"{token}_state.upload_state"
+ full_state_name = upload_file.get_full_state_name(["_upload_state"])
+ state_name = upload_file.get_state_name("_upload_state")
+ substate_token = f"{token}_{full_state_name}"
upload_box = driver.find_element(By.XPATH, "//input[@type='file']")
assert upload_box
@@ -260,7 +265,7 @@ async def test_upload_file_multiple(tmp_path, upload_file: AppHarness, driver):
async def get_file_data():
return (
(await upload_file.get_state(substate_token))
- .substates["upload_state"]
+ .substates[state_name]
._file_data
)
@@ -342,7 +347,9 @@ async def test_cancel_upload(tmp_path, upload_file: AppHarness, driver: WebDrive
# wait for the backend connection to send the token
token = upload_file.poll_for_value(token_input)
assert token is not None
- substate_token = f"{token}_state.upload_state"
+ state_name = upload_file.get_state_name("_upload_state")
+ state_full_name = upload_file.get_full_state_name(["_upload_state"])
+ substate_token = f"{token}_{state_full_name}"
upload_box = driver.find_elements(By.XPATH, "//input[@type='file']")[1]
upload_button = driver.find_element(By.ID, f"upload_button_secondary")
@@ -361,7 +368,7 @@ async def test_cancel_upload(tmp_path, upload_file: AppHarness, driver: WebDrive
# look up the backend state and assert on progress
state = await upload_file.get_state(substate_token)
- assert state.substates["upload_state"].progress_dicts
- assert exp_name not in state.substates["upload_state"]._file_data
+ assert state.substates[state_name].progress_dicts
+ assert exp_name not in state.substates[state_name]._file_data
target_file.unlink()
diff --git a/tests/integration/test_urls.py b/tests/integration/test_urls.py
new file mode 100755
index 000000000..81689aa18
--- /dev/null
+++ b/tests/integration/test_urls.py
@@ -0,0 +1,68 @@
+"""Integration tests for all urls in Reflex."""
+
+import os
+import re
+from pathlib import Path
+
+import pytest
+import requests
+
+
+def check_urls(repo_dir: Path):
+ """Check that all URLs in the repo are valid and secure.
+
+ Args:
+ repo_dir: The directory of the repo.
+
+ Returns:
+ A list of errors.
+ """
+ url_pattern = re.compile(r'http[s]?://reflex\.dev[^\s")]*')
+ errors = []
+
+ for root, _dirs, files in os.walk(repo_dir):
+ root = Path(root)
+ if root.stem == "__pycache__":
+ continue
+
+ for file_name in files:
+ if not file_name.endswith(".py") and not file_name.endswith(".md"):
+ continue
+
+ file_path = root / file_name
+ try:
+ for line in file_path.read_text().splitlines():
+ urls = url_pattern.findall(line)
+ for url in set(urls):
+ if url.startswith("http://"):
+ errors.append(
+ f"Found insecure HTTP URL: {url} in {file_path}"
+ )
+ url = url.strip('"\n')
+ try:
+ response = requests.head(
+ url, allow_redirects=True, timeout=5
+ )
+ response.raise_for_status()
+ except requests.RequestException as e:
+ errors.append(
+ f"Error accessing URL: {url} in {file_path} | Error: {e}, , Check your path ends with a /"
+ )
+ except Exception as e:
+ errors.append(f"Error reading file: {file_path} | Error: {e}")
+
+ return errors
+
+
+@pytest.mark.parametrize(
+ "repo_dir",
+ [Path(__file__).resolve().parent.parent / "reflex"],
+)
+def test_find_and_check_urls(repo_dir: Path):
+ """Test that all URLs in the repo are valid and secure.
+
+ Args:
+ repo_dir: The directory of the repo.
+ """
+ errors = check_urls(repo_dir)
+ assert not errors, "\n".join(errors)
diff --git a/integration/test_var_operations.py b/tests/integration/test_var_operations.py
similarity index 95%
rename from integration/test_var_operations.py
rename to tests/integration/test_var_operations.py
index 9f8803dbe..cae56e1a8 100644
--- a/integration/test_var_operations.py
+++ b/tests/integration/test_var_operations.py
@@ -1,4 +1,5 @@
"""Integration tests for var operations."""
+
from typing import Generator
import pytest
@@ -14,6 +15,11 @@ def VarOperations():
from typing import Dict, List
import reflex as rx
+ from reflex.vars.base import LiteralVar
+ from reflex.vars.sequence import ArrayVar
+
+ class Object(rx.Base):
+ str: str = "hello"
class VarOperationState(rx.State):
int_var1: int = 10
@@ -24,12 +30,13 @@ def VarOperations():
list1: List = [1, 2]
list2: List = [3, 4]
list3: List = ["first", "second", "third"]
+ list4: List = [Object(name="obj_1"), Object(name="obj_2")]
str_var1: str = "first"
str_var2: str = "second"
str_var3: str = "ThIrD"
str_var4: str = "a long string"
- dict1: Dict = {1: 2}
- dict2: Dict = {3: 4}
+ dict1: Dict[int, int] = {1: 2}
+ dict2: Dict[int, int] = {3: 4}
html_str: str = "
hello
"
app = rx.App(state=rx.State)
@@ -469,6 +476,7 @@ def VarOperations():
rx.text(
VarOperationState.list1.contains(1).to_string(), id="list_contains"
),
+ rx.text(VarOperationState.list4.pluck("name").to_string(), id="list_pluck"),
rx.text(VarOperationState.list1.reverse().to_string(), id="list_reverse"),
# LIST, INT
rx.text(
@@ -542,33 +550,30 @@ def VarOperations():
VarOperationState.html_str,
id="html_str",
),
- rx.chakra.highlight(
- "second",
- query=[VarOperationState.str_var2],
- ),
- rx.text(rx.Var.range(2, 5).join(","), id="list_join_range1"),
- rx.text(rx.Var.range(2, 10, 2).join(","), id="list_join_range2"),
- rx.text(rx.Var.range(5, 0, -1).join(","), id="list_join_range3"),
- rx.text(rx.Var.range(0, 3).join(","), id="list_join_range4"),
+ rx.el.mark("second"),
+ rx.text(ArrayVar.range(2, 5).join(","), id="list_join_range1"),
+ rx.text(ArrayVar.range(2, 10, 2).join(","), id="list_join_range2"),
+ rx.text(ArrayVar.range(5, 0, -1).join(","), id="list_join_range3"),
+ rx.text(ArrayVar.range(0, 3).join(","), id="list_join_range4"),
rx.box(
rx.foreach(
- rx.Var.range(0, 2),
+ ArrayVar.range(0, 2),
lambda x: rx.text(VarOperationState.list1[x], as_="p"),
),
id="foreach_list_arg",
),
rx.box(
rx.foreach(
- rx.Var.range(0, 2),
+ ArrayVar.range(0, 2),
lambda x, ix: rx.text(VarOperationState.list1[ix], as_="p"),
),
id="foreach_list_ix",
),
rx.box(
rx.foreach(
- rx.Var.create_safe(list(range(0, 3))).to(List[int]),
+ LiteralVar.create(list(range(0, 3))).to(ArrayVar, List[int]),
lambda x: rx.foreach(
- rx.Var.range(x),
+ ArrayVar.range(x),
lambda y: rx.text(VarOperationState.list1[y], as_="p"),
),
),
@@ -583,6 +588,16 @@ def VarOperations():
int_var2=VarOperationState.int_var2,
id="memo_comp_nested",
),
+ # foreach in a match
+ rx.box(
+ rx.match(
+ VarOperationState.list3.length(),
+ (0, rx.text("No choices")),
+ (1, rx.text("One choice")),
+ rx.foreach(VarOperationState.list3, lambda choice: rx.text(choice)),
+ ),
+ id="foreach_in_match",
+ ),
)
@@ -744,6 +759,7 @@ def test_var_operations(driver, var_operations: AppHarness):
("list_and_list", "[3,4]"),
("list_or_list", "[1,2]"),
("list_contains", "true"),
+ ("list_pluck", '["obj_1","obj_2"]'),
("list_reverse", "[2,1]"),
("list_join", "firstsecondthird"),
("list_join_comma", "first,second,third"),
@@ -779,9 +795,12 @@ def test_var_operations(driver, var_operations: AppHarness):
# rx.memo component with state
("memo_comp", "1210"),
("memo_comp_nested", "345"),
+ # foreach in a match
+ ("foreach_in_match", "first\nsecond\nthird"),
]
for tag, expected in tests:
+ print(tag)
assert driver.find_element(By.ID, tag).text == expected
# Highlight component with var query (does not plumb ID)
diff --git a/tests/integration/tests_playwright/test_stateless_app.py b/tests/integration/tests_playwright/test_stateless_app.py
new file mode 100644
index 000000000..129b69dc7
--- /dev/null
+++ b/tests/integration/tests_playwright/test_stateless_app.py
@@ -0,0 +1,59 @@
+"""Integration tests for a stateless app."""
+
+from typing import Generator
+
+import httpx
+import pytest
+from playwright.sync_api import Page, expect
+
+import reflex as rx
+from reflex.testing import AppHarness
+
+
+def StatelessApp():
+ """A stateless app that renders a heading."""
+ import reflex as rx
+
+ def index():
+ return rx.heading("This is a stateless app")
+
+ app = rx.App()
+ app.add_page(index)
+
+
+@pytest.fixture(scope="module")
+def stateless_app(tmp_path_factory) -> Generator[AppHarness, None, None]:
+ """Create a stateless app AppHarness.
+
+ Args:
+ tmp_path_factory: pytest fixture for creating temporary directories.
+
+ Yields:
+ AppHarness: A harness for testing the stateless app.
+ """
+ with AppHarness.create(
+ root=tmp_path_factory.mktemp("stateless_app"),
+ app_source=StatelessApp, # type: ignore
+ ) as harness:
+ yield harness
+
+
+def test_statelessness(stateless_app: AppHarness, page: Page):
+ """Test that the stateless app renders a heading but backend/_event is not mounted.
+
+ Args:
+ stateless_app: A harness for testing the stateless app.
+ page: A Playwright page.
+ """
+ assert stateless_app.frontend_url is not None
+ assert stateless_app.backend is not None
+ assert stateless_app.backend.started
+
+ res = httpx.get(rx.config.get_config().api_url + "/_event")
+ assert res.status_code == 404
+
+ res2 = httpx.get(rx.config.get_config().api_url + "/ping")
+ assert res2.status_code == 200
+
+ page.goto(stateless_app.frontend_url)
+ expect(page.get_by_role("heading")).to_have_text("This is a stateless app")
diff --git a/tests/integration/tests_playwright/test_table.py b/tests/integration/tests_playwright/test_table.py
new file mode 100644
index 000000000..917247b89
--- /dev/null
+++ b/tests/integration/tests_playwright/test_table.py
@@ -0,0 +1,100 @@
+"""Integration tests for table and related components."""
+
+from typing import Generator
+
+import pytest
+from playwright.sync_api import Page
+
+from reflex.testing import AppHarness
+
+expected_col_headers = ["Name", "Age", "Location"]
+expected_row_headers = ["John", "Jane", "Joe"]
+expected_cells_data = [
+ ["30", "New York"],
+ ["31", "San Fransisco"],
+ ["32", "Los Angeles"],
+]
+
+
+def Table():
+ """App using table component."""
+ import reflex as rx
+
+ app = rx.App(state=rx.State)
+
+ @app.add_page
+ def index():
+ return rx.center(
+ rx.table.root(
+ rx.table.header(
+ rx.table.row(
+ rx.table.column_header_cell("Name"),
+ rx.table.column_header_cell("Age"),
+ rx.table.column_header_cell("Location"),
+ ),
+ ),
+ rx.table.body(
+ rx.table.row(
+ rx.table.row_header_cell("John"),
+ rx.table.cell(30),
+ rx.table.cell("New York"),
+ ),
+ rx.table.row(
+ rx.table.row_header_cell("Jane"),
+ rx.table.cell(31),
+ rx.table.cell("San Fransisco"),
+ ),
+ rx.table.row(
+ rx.table.row_header_cell("Joe"),
+ rx.table.cell(32),
+ rx.table.cell("Los Angeles"),
+ ),
+ ),
+ width="100%",
+ ),
+ )
+
+
+@pytest.fixture()
+def table_app(tmp_path_factory) -> Generator[AppHarness, None, None]:
+ """Start Table app at tmp_path via AppHarness.
+
+ Args:
+ tmp_path_factory: pytest tmp_path_factory fixture
+
+ Yields:
+ running AppHarness instance
+
+ """
+ with AppHarness.create(
+ root=tmp_path_factory.mktemp("table"),
+ app_source=Table, # type: ignore
+ ) as harness:
+ assert harness.app_instance is not None, "app is not running"
+ yield harness
+
+
+def test_table(page: Page, table_app: AppHarness):
+ """Test that a table component is rendered properly.
+
+ Args:
+ table_app: Harness for Table app
+ page: Playwright page instance
+ """
+ assert table_app.frontend_url is not None, "frontend url is not available"
+
+ page.goto(table_app.frontend_url)
+ table = page.get_by_role("table")
+
+ # Check column headers
+ headers = table.get_by_role("columnheader").all_inner_texts()
+ assert headers == expected_col_headers
+
+ # Check rows headers
+ rows = table.get_by_role("rowheader").all_inner_texts()
+ assert rows == expected_row_headers
+
+ # Check cells
+ rows = table.get_by_role("cell").all_inner_texts()
+ for i, expected_row in enumerate(expected_cells_data):
+ assert [rows[idx := i * 2], rows[idx + 1]] == expected_row
diff --git a/integration/utils.py b/tests/integration/utils.py
similarity index 86%
rename from integration/utils.py
rename to tests/integration/utils.py
index bcbd6c497..d993ea720 100644
--- a/integration/utils.py
+++ b/tests/integration/utils.py
@@ -1,4 +1,5 @@
"""Helper utilities for integration tests."""
+
from __future__ import annotations
from contextlib import contextmanager
@@ -54,7 +55,9 @@ class LocalStorage:
Returns:
The number of items in local storage.
"""
- return int(self.driver.execute_script("return window.localStorage.length;"))
+ return int(
+ self.driver.execute_script(f"return window.{self.storage_key}.length;")
+ )
def items(self) -> dict[str, str]:
"""Get all items in local storage.
@@ -63,7 +66,7 @@ class LocalStorage:
A dict mapping keys to values.
"""
return self.driver.execute_script(
- "var ls = window.localStorage, items = {}; "
+ f"var ls = window.{self.storage_key}, items = {{}}; "
"for (var i = 0, k; i < ls.length; ++i) "
" items[k = ls.key(i)] = ls.getItem(k); "
"return items; "
@@ -76,7 +79,7 @@ class LocalStorage:
A list of keys.
"""
return self.driver.execute_script(
- "var ls = window.localStorage, keys = []; "
+ f"var ls = window.{self.storage_key}, keys = []; "
"for (var i = 0; i < ls.length; ++i) "
" keys[i] = ls.key(i); "
"return keys; "
@@ -92,7 +95,7 @@ class LocalStorage:
The value of the key.
"""
return self.driver.execute_script(
- "return window.localStorage.getItem(arguments[0]);", key
+ f"return window.{self.storage_key}.getItem(arguments[0]);", key
)
def set(self, key, value) -> None:
@@ -103,7 +106,9 @@ class LocalStorage:
value: The value to set the key to.
"""
self.driver.execute_script(
- "window.localStorage.setItem(arguments[0], arguments[1]);", key, value
+ f"window.{self.storage_key}.setItem(arguments[0], arguments[1]);",
+ key,
+ value,
)
def has(self, key) -> bool:
@@ -123,11 +128,13 @@ class LocalStorage:
Args:
key: The key to remove.
"""
- self.driver.execute_script("window.localStorage.removeItem(arguments[0]);", key)
+ self.driver.execute_script(
+ f"window.{self.storage_key}.removeItem(arguments[0]);", key
+ )
def clear(self) -> None:
"""Clear all local storage."""
- self.driver.execute_script("window.localStorage.clear();")
+ self.driver.execute_script(f"window.{self.storage_key}.clear();")
def __getitem__(self, key) -> str:
"""Get a key from local storage.
diff --git a/tests/test_init.py b/tests/test_init.py
deleted file mode 100644
index 4f511983b..000000000
--- a/tests/test_init.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from reflex import _reverse_mapping # type: ignore
-
-
-def test__reverse_mapping():
- assert _reverse_mapping({"a": ["b"], "c": ["d"]}) == {"b": "a", "d": "c"}
-
-
-def test__reverse_mapping_duplicate():
- assert _reverse_mapping({"a": ["b", "c"], "d": ["b"]}) == {"b": "a", "c": "a"}
diff --git a/tests/test_node_version.py b/tests/test_node_version.py
new file mode 100644
index 000000000..9555eb524
--- /dev/null
+++ b/tests/test_node_version.py
@@ -0,0 +1,73 @@
+"""Test for latest node version being able to run reflex."""
+
+from __future__ import annotations
+
+from typing import Any, Generator
+
+import httpx
+import pytest
+from playwright.sync_api import Page, expect
+
+from reflex.testing import AppHarness
+
+
+def TestNodeVersionApp():
+ """A test app for node latest version."""
+ import reflex as rx
+ from reflex.utils.prerequisites import get_node_version
+
+ class TestNodeVersionConfig(rx.Config):
+ pass
+
+ class TestNodeVersionState(rx.State):
+ @rx.var
+ def node_version(self) -> str:
+ return str(get_node_version())
+
+ app = rx.App()
+
+ @app.add_page
+ def index():
+ return rx.heading("Node Version check v", TestNodeVersionState.node_version)
+
+
+@pytest.fixture()
+def node_version_app(tmp_path) -> Generator[AppHarness, Any, None]:
+ """Fixture to start TestNodeVersionApp app at tmp_path via AppHarness.
+
+ Args:
+ tmp_path: pytest tmp_path fixture
+
+ Yields:
+ running AppHarness instance
+ """
+ with AppHarness.create(
+ root=tmp_path,
+ app_source=TestNodeVersionApp, # type: ignore
+ ) as harness:
+ yield harness
+
+
+def test_node_version(node_version_app: AppHarness, page: Page):
+ """Test for latest node version being able to run reflex.
+
+ Args:
+ node_version_app: running AppHarness instance
+ page: playwright page instance
+ """
+
+ def get_latest_node_version():
+ response = httpx.get("https://nodejs.org/dist/index.json")
+ versions = response.json()
+
+ # Assuming the first entry in the API response is the most recent version
+ if versions:
+ latest_version = versions[0]["version"]
+ return latest_version
+ return None
+
+ assert node_version_app.frontend_url is not None
+ page.goto(node_version_app.frontend_url)
+ expect(page.get_by_role("heading")).to_have_text(
+ f"Node Version check {get_latest_node_version()}"
+ )
diff --git a/tests/test_var.py b/tests/test_var.py
deleted file mode 100644
index a58c49392..000000000
--- a/tests/test_var.py
+++ /dev/null
@@ -1,1387 +0,0 @@
-import json
-import typing
-from typing import Dict, List, Set, Tuple
-
-import pytest
-from pandas import DataFrame
-
-from reflex.base import Base
-from reflex.state import BaseState
-from reflex.vars import (
- BaseVar,
- Var,
- computed_var,
-)
-
-test_vars = [
- BaseVar(_var_name="prop1", _var_type=int),
- BaseVar(_var_name="key", _var_type=str),
- BaseVar(_var_name="value", _var_type=str)._var_set_state("state"),
- BaseVar(_var_name="local", _var_type=str, _var_is_local=True)._var_set_state(
- "state"
- ),
- BaseVar(_var_name="local2", _var_type=str, _var_is_local=True),
-]
-
-
-class ATestState(BaseState):
- """Test state."""
-
- value: str
- dict_val: Dict[str, List] = {}
-
-
-@pytest.fixture
-def TestObj():
- class TestObj(Base):
- foo: int
- bar: str
-
- return TestObj
-
-
-@pytest.fixture
-def ParentState(TestObj):
- class ParentState(BaseState):
- foo: int
- bar: int
-
- @computed_var
- def var_without_annotation(self):
- return TestObj
-
- return ParentState
-
-
-@pytest.fixture
-def ChildState(ParentState, TestObj):
- class ChildState(ParentState):
- @computed_var
- def var_without_annotation(self):
- return TestObj
-
- return ChildState
-
-
-@pytest.fixture
-def GrandChildState(ChildState, TestObj):
- class GrandChildState(ChildState):
- @computed_var
- def var_without_annotation(self):
- return TestObj
-
- return GrandChildState
-
-
-@pytest.fixture
-def StateWithAnyVar(TestObj):
- class StateWithAnyVar(BaseState):
- @computed_var
- def var_without_annotation(self) -> typing.Any:
- return TestObj
-
- return StateWithAnyVar
-
-
-@pytest.fixture
-def StateWithCorrectVarAnnotation():
- class StateWithCorrectVarAnnotation(BaseState):
- @computed_var
- def var_with_annotation(self) -> str:
- return "Correct annotation"
-
- return StateWithCorrectVarAnnotation
-
-
-@pytest.fixture
-def StateWithWrongVarAnnotation(TestObj):
- class StateWithWrongVarAnnotation(BaseState):
- @computed_var
- def var_with_annotation(self) -> str:
- return TestObj
-
- return StateWithWrongVarAnnotation
-
-
-@pytest.fixture
-def StateWithInitialComputedVar():
- class StateWithInitialComputedVar(BaseState):
- @computed_var(initial_value="Initial value")
- def var_with_initial_value(self) -> str:
- return "Runtime value"
-
- return StateWithInitialComputedVar
-
-
-@pytest.fixture
-def ChildWithInitialComputedVar(StateWithInitialComputedVar):
- class ChildWithInitialComputedVar(StateWithInitialComputedVar):
- @computed_var(initial_value="Initial value")
- def var_with_initial_value_child(self) -> str:
- return "Runtime value"
-
- return ChildWithInitialComputedVar
-
-
-@pytest.fixture
-def StateWithRuntimeOnlyVar():
- class StateWithRuntimeOnlyVar(BaseState):
- @computed_var(initial_value=None)
- def var_raises_at_runtime(self) -> str:
- raise ValueError("So nicht, mein Freund")
-
- return StateWithRuntimeOnlyVar
-
-
-@pytest.fixture
-def ChildWithRuntimeOnlyVar(StateWithRuntimeOnlyVar):
- class ChildWithRuntimeOnlyVar(StateWithRuntimeOnlyVar):
- @computed_var(initial_value="Initial value")
- def var_raises_at_runtime_child(self) -> str:
- raise ValueError("So nicht, mein Freund")
-
- return ChildWithRuntimeOnlyVar
-
-
-@pytest.mark.parametrize(
- "prop,expected",
- zip(
- test_vars,
- [
- "prop1",
- "key",
- "state.value",
- "state.local",
- "local2",
- ],
- ),
-)
-def test_full_name(prop, expected):
- """Test that the full name of a var is correct.
-
- Args:
- prop: The var to test.
- expected: The expected full name.
- """
- assert prop._var_full_name == expected
-
-
-@pytest.mark.parametrize(
- "prop,expected",
- zip(
- test_vars,
- ["{prop1}", "{key}", "{state.value}", "state.local", "local2"],
- ),
-)
-def test_str(prop, expected):
- """Test that the string representation of a var is correct.
-
- Args:
- prop: The var to test.
- expected: The expected string representation.
- """
- assert str(prop) == expected
-
-
-@pytest.mark.parametrize(
- "prop,expected",
- [
- (BaseVar(_var_name="p", _var_type=int), 0),
- (BaseVar(_var_name="p", _var_type=float), 0.0),
- (BaseVar(_var_name="p", _var_type=str), ""),
- (BaseVar(_var_name="p", _var_type=bool), False),
- (BaseVar(_var_name="p", _var_type=list), []),
- (BaseVar(_var_name="p", _var_type=dict), {}),
- (BaseVar(_var_name="p", _var_type=tuple), ()),
- (BaseVar(_var_name="p", _var_type=set), set()),
- ],
-)
-def test_default_value(prop, expected):
- """Test that the default value of a var is correct.
-
- Args:
- prop: The var to test.
- expected: The expected default value.
- """
- assert prop.get_default_value() == expected
-
-
-@pytest.mark.parametrize(
- "prop,expected",
- zip(
- test_vars,
- [
- "set_prop1",
- "set_key",
- "state.set_value",
- "state.set_local",
- "set_local2",
- ],
- ),
-)
-def test_get_setter(prop, expected):
- """Test that the name of the setter function of a var is correct.
-
- Args:
- prop: The var to test.
- expected: The expected name of the setter function.
- """
- assert prop.get_setter_name() == expected
-
-
-@pytest.mark.parametrize(
- "value,expected",
- [
- (None, None),
- (1, BaseVar(_var_name="1", _var_type=int, _var_is_local=True)),
- ("key", BaseVar(_var_name="key", _var_type=str, _var_is_local=True)),
- (3.14, BaseVar(_var_name="3.14", _var_type=float, _var_is_local=True)),
- ([1, 2, 3], BaseVar(_var_name="[1, 2, 3]", _var_type=list, _var_is_local=True)),
- (
- {"a": 1, "b": 2},
- BaseVar(_var_name='{"a": 1, "b": 2}', _var_type=dict, _var_is_local=True),
- ),
- ],
-)
-def test_create(value, expected):
- """Test the var create function.
-
- Args:
- value: The value to create a var from.
- expected: The expected name of the setter function.
- """
- prop = Var.create(value)
- if value is None:
- assert prop == expected
- else:
- assert prop.equals(expected) # type: ignore
-
-
-def test_create_type_error():
- """Test the var create function when inputs type error."""
-
- class ErrorType:
- pass
-
- value = ErrorType()
-
- with pytest.raises(TypeError):
- Var.create(value)
-
-
-def v(value) -> Var:
- val = (
- Var.create(json.dumps(value), _var_is_string=True, _var_is_local=False)
- if isinstance(value, str)
- else Var.create(value, _var_is_local=False)
- )
- assert val is not None
- return val
-
-
-def test_basic_operations(TestObj):
- """Test the var operations.
-
- Args:
- TestObj: The test object.
- """
- assert str(v(1) == v(2)) == "{((1) === (2))}"
- assert str(v(1) != v(2)) == "{((1) !== (2))}"
- assert str(v(1) < v(2)) == "{((1) < (2))}"
- assert str(v(1) <= v(2)) == "{((1) <= (2))}"
- assert str(v(1) > v(2)) == "{((1) > (2))}"
- assert str(v(1) >= v(2)) == "{((1) >= (2))}"
- assert str(v(1) + v(2)) == "{((1) + (2))}"
- assert str(v(1) - v(2)) == "{((1) - (2))}"
- assert str(v(1) * v(2)) == "{((1) * (2))}"
- assert str(v(1) / v(2)) == "{((1) / (2))}"
- assert str(v(1) // v(2)) == "{Math.floor((1) / (2))}"
- assert str(v(1) % v(2)) == "{((1) % (2))}"
- assert str(v(1) ** v(2)) == "{Math.pow((1) , (2))}"
- assert str(v(1) & v(2)) == "{((1) && (2))}"
- assert str(v(1) | v(2)) == "{((1) || (2))}"
- assert str(v([1, 2, 3])[v(0)]) == "{[1, 2, 3].at(0)}"
- assert str(v({"a": 1, "b": 2})["a"]) == '{{"a": 1, "b": 2}["a"]}'
- assert str(v("foo") == v("bar")) == '{(("foo") === ("bar"))}'
- assert (
- str(
- Var.create("foo", _var_is_local=False)
- == Var.create("bar", _var_is_local=False)
- )
- == "{((foo) === (bar))}"
- )
- assert (
- str(
- BaseVar(
- _var_name="foo", _var_type=str, _var_is_string=True, _var_is_local=True
- )
- == BaseVar(
- _var_name="bar", _var_type=str, _var_is_string=True, _var_is_local=True
- )
- )
- == "((`foo`) === (`bar`))"
- )
- assert (
- str(
- BaseVar(
- _var_name="foo",
- _var_type=TestObj,
- _var_is_string=True,
- _var_is_local=False,
- )
- ._var_set_state("state")
- .bar
- == BaseVar(
- _var_name="bar", _var_type=str, _var_is_string=True, _var_is_local=True
- )
- )
- == "{((state.foo.bar) === (`bar`))}"
- )
- assert (
- str(BaseVar(_var_name="foo", _var_type=TestObj)._var_set_state("state").bar)
- == "{state.foo.bar}"
- )
- assert str(abs(v(1))) == "{Math.abs(1)}"
- assert str(v([1, 2, 3]).length()) == "{[1, 2, 3].length}"
- assert str(v([1, 2]) + v([3, 4])) == "{spreadArraysOrObjects(([1, 2]) , ([3, 4]))}"
-
- # Tests for reverse operation
- assert str(v([1, 2, 3]).reverse()) == "{[...[1, 2, 3]].reverse()}"
- assert str(v(["1", "2", "3"]).reverse()) == '{[...["1", "2", "3"]].reverse()}'
- assert (
- str(BaseVar(_var_name="foo", _var_type=list)._var_set_state("state").reverse())
- == "{[...state.foo].reverse()}"
- )
- assert (
- str(BaseVar(_var_name="foo", _var_type=list).reverse())
- == "{[...foo].reverse()}"
- )
- assert str(BaseVar(_var_name="foo", _var_type=str)._type()) == "{typeof foo}" # type: ignore
- assert (
- str(BaseVar(_var_name="foo", _var_type=str)._type() == str) # type: ignore
- == "{((typeof foo) === (`string`))}"
- )
- assert (
- str(BaseVar(_var_name="foo", _var_type=str)._type() == str) # type: ignore
- == "{((typeof foo) === (`string`))}"
- )
- assert (
- str(BaseVar(_var_name="foo", _var_type=str)._type() == int) # type: ignore
- == "{((typeof foo) === (`number`))}"
- )
- assert (
- str(BaseVar(_var_name="foo", _var_type=str)._type() == list) # type: ignore
- == "{((typeof foo) === (`Array`))}"
- )
- assert (
- str(BaseVar(_var_name="foo", _var_type=str)._type() == float) # type: ignore
- == "{((typeof foo) === (`number`))}"
- )
- assert (
- str(BaseVar(_var_name="foo", _var_type=str)._type() == tuple) # type: ignore
- == "{((typeof foo) === (`Array`))}"
- )
- assert (
- str(BaseVar(_var_name="foo", _var_type=str)._type() == dict) # type: ignore
- == "{((typeof foo) === (`Object`))}"
- )
- assert (
- str(BaseVar(_var_name="foo", _var_type=str)._type() != str) # type: ignore
- == "{((typeof foo) !== (`string`))}"
- )
- assert (
- str(BaseVar(_var_name="foo", _var_type=str)._type() != int) # type: ignore
- == "{((typeof foo) !== (`number`))}"
- )
- assert (
- str(BaseVar(_var_name="foo", _var_type=str)._type() != list) # type: ignore
- == "{((typeof foo) !== (`Array`))}"
- )
- assert (
- str(BaseVar(_var_name="foo", _var_type=str)._type() != float) # type: ignore
- == "{((typeof foo) !== (`number`))}"
- )
- assert (
- str(BaseVar(_var_name="foo", _var_type=str)._type() != tuple) # type: ignore
- == "{((typeof foo) !== (`Array`))}"
- )
- assert (
- str(BaseVar(_var_name="foo", _var_type=str)._type() != dict) # type: ignore
- == "{((typeof foo) !== (`Object`))}"
- )
-
-
-@pytest.mark.parametrize(
- "var, expected",
- [
- (v([1, 2, 3]), "[1, 2, 3]"),
- (v(set([1, 2, 3])), "[1, 2, 3]"),
- (v(["1", "2", "3"]), '["1", "2", "3"]'),
- (BaseVar(_var_name="foo", _var_type=list)._var_set_state("state"), "state.foo"),
- (BaseVar(_var_name="foo", _var_type=list), "foo"),
- (v((1, 2, 3)), "[1, 2, 3]"),
- (v(("1", "2", "3")), '["1", "2", "3"]'),
- (
- BaseVar(_var_name="foo", _var_type=tuple)._var_set_state("state"),
- "state.foo",
- ),
- (BaseVar(_var_name="foo", _var_type=tuple), "foo"),
- ],
-)
-def test_list_tuple_contains(var, expected):
- assert str(var.contains(1)) == f"{{{expected}.includes(1)}}"
- assert str(var.contains("1")) == f'{{{expected}.includes("1")}}'
- assert str(var.contains(v(1))) == f"{{{expected}.includes(1)}}"
- assert str(var.contains(v("1"))) == f'{{{expected}.includes("1")}}'
- other_state_var = BaseVar(_var_name="other", _var_type=str)._var_set_state("state")
- other_var = BaseVar(_var_name="other", _var_type=str)
- assert str(var.contains(other_state_var)) == f"{{{expected}.includes(state.other)}}"
- assert str(var.contains(other_var)) == f"{{{expected}.includes(other)}}"
-
-
-@pytest.mark.parametrize(
- "var, expected",
- [
- (v("123"), json.dumps("123")),
- (BaseVar(_var_name="foo", _var_type=str)._var_set_state("state"), "state.foo"),
- (BaseVar(_var_name="foo", _var_type=str), "foo"),
- ],
-)
-def test_str_contains(var, expected):
- assert str(var.contains("1")) == f'{{{expected}.includes("1")}}'
- assert str(var.contains(v("1"))) == f'{{{expected}.includes("1")}}'
- other_state_var = BaseVar(_var_name="other", _var_type=str)._var_set_state("state")
- other_var = BaseVar(_var_name="other", _var_type=str)
- assert str(var.contains(other_state_var)) == f"{{{expected}.includes(state.other)}}"
- assert str(var.contains(other_var)) == f"{{{expected}.includes(other)}}"
-
-
-@pytest.mark.parametrize(
- "var, expected",
- [
- (v({"a": 1, "b": 2}), '{"a": 1, "b": 2}'),
- (BaseVar(_var_name="foo", _var_type=dict)._var_set_state("state"), "state.foo"),
- (BaseVar(_var_name="foo", _var_type=dict), "foo"),
- ],
-)
-def test_dict_contains(var, expected):
- assert str(var.contains(1)) == f"{{{expected}.hasOwnProperty(1)}}"
- assert str(var.contains("1")) == f'{{{expected}.hasOwnProperty("1")}}'
- assert str(var.contains(v(1))) == f"{{{expected}.hasOwnProperty(1)}}"
- assert str(var.contains(v("1"))) == f'{{{expected}.hasOwnProperty("1")}}'
- other_state_var = BaseVar(_var_name="other", _var_type=str)._var_set_state("state")
- other_var = BaseVar(_var_name="other", _var_type=str)
- assert (
- str(var.contains(other_state_var))
- == f"{{{expected}.hasOwnProperty(state.other)}}"
- )
- assert str(var.contains(other_var)) == f"{{{expected}.hasOwnProperty(other)}}"
-
-
-@pytest.mark.parametrize(
- "var",
- [
- BaseVar(_var_name="list", _var_type=List[int]),
- BaseVar(_var_name="tuple", _var_type=Tuple[int, int]),
- BaseVar(_var_name="str", _var_type=str),
- ],
-)
-def test_var_indexing_lists(var):
- """Test that we can index into str, list or tuple vars.
-
- Args:
- var : The str, list or tuple base var.
- """
- # Test basic indexing.
- assert str(var[0]) == f"{{{var._var_name}.at(0)}}"
- assert str(var[1]) == f"{{{var._var_name}.at(1)}}"
-
- # Test negative indexing.
- assert str(var[-1]) == f"{{{var._var_name}.at(-1)}}"
-
-
-@pytest.mark.parametrize(
- "var, type_",
- [
- (BaseVar(_var_name="list", _var_type=List[int]), [int, int]),
- (BaseVar(_var_name="tuple", _var_type=Tuple[int, str]), [int, str]),
- ],
-)
-def test_var_indexing_types(var, type_):
- """Test that indexing returns valid types.
-
- Args:
- var : The list, typle base var.
- type_ : The type on indexed object.
-
- """
- assert var[2]._var_type == type_[0]
- assert var[3]._var_type == type_[1]
-
-
-def test_var_indexing_str():
- """Test that we can index into str vars."""
- str_var = BaseVar(_var_name="str", _var_type=str)
-
- # Test that indexing gives a type of Var[str].
- assert isinstance(str_var[0], Var)
- assert str_var[0]._var_type == str
-
- # Test basic indexing.
- assert str(str_var[0]) == "{str.at(0)}"
- assert str(str_var[1]) == "{str.at(1)}"
-
- # Test negative indexing.
- assert str(str_var[-1]) == "{str.at(-1)}"
-
-
-@pytest.mark.parametrize(
- "var, index",
- [
- (BaseVar(_var_name="lst", _var_type=List[int]), [1, 2]),
- (BaseVar(_var_name="lst", _var_type=List[int]), {"name": "dict"}),
- (BaseVar(_var_name="lst", _var_type=List[int]), {"set"}),
- (
- BaseVar(_var_name="lst", _var_type=List[int]),
- (
- 1,
- 2,
- ),
- ),
- (BaseVar(_var_name="lst", _var_type=List[int]), 1.5),
- (BaseVar(_var_name="lst", _var_type=List[int]), "str"),
- (
- BaseVar(_var_name="lst", _var_type=List[int]),
- BaseVar(_var_name="string_var", _var_type=str),
- ),
- (
- BaseVar(_var_name="lst", _var_type=List[int]),
- BaseVar(_var_name="float_var", _var_type=float),
- ),
- (
- BaseVar(_var_name="lst", _var_type=List[int]),
- BaseVar(_var_name="list_var", _var_type=List[int]),
- ),
- (
- BaseVar(_var_name="lst", _var_type=List[int]),
- BaseVar(_var_name="set_var", _var_type=Set[str]),
- ),
- (
- BaseVar(_var_name="lst", _var_type=List[int]),
- BaseVar(_var_name="dict_var", _var_type=Dict[str, str]),
- ),
- (BaseVar(_var_name="str", _var_type=str), [1, 2]),
- (BaseVar(_var_name="lst", _var_type=str), {"name": "dict"}),
- (BaseVar(_var_name="lst", _var_type=str), {"set"}),
- (
- BaseVar(_var_name="lst", _var_type=str),
- BaseVar(_var_name="string_var", _var_type=str),
- ),
- (
- BaseVar(_var_name="lst", _var_type=str),
- BaseVar(_var_name="float_var", _var_type=float),
- ),
- (BaseVar(_var_name="str", _var_type=Tuple[str]), [1, 2]),
- (BaseVar(_var_name="lst", _var_type=Tuple[str]), {"name": "dict"}),
- (BaseVar(_var_name="lst", _var_type=Tuple[str]), {"set"}),
- (
- BaseVar(_var_name="lst", _var_type=Tuple[str]),
- BaseVar(_var_name="string_var", _var_type=str),
- ),
- (
- BaseVar(_var_name="lst", _var_type=Tuple[str]),
- BaseVar(_var_name="float_var", _var_type=float),
- ),
- ],
-)
-def test_var_unsupported_indexing_lists(var, index):
- """Test unsupported indexing throws a type error.
-
- Args:
- var: The base var.
- index: The base var index.
- """
- with pytest.raises(TypeError):
- var[index]
-
-
-@pytest.mark.parametrize(
- "var",
- [
- BaseVar(_var_name="lst", _var_type=List[int]),
- BaseVar(_var_name="tuple", _var_type=Tuple[int, int]),
- BaseVar(_var_name="str", _var_type=str),
- ],
-)
-def test_var_list_slicing(var):
- """Test that we can slice into str, list or tuple vars.
-
- Args:
- var : The str, list or tuple base var.
- """
- assert str(var[:1]) == f"{{{var._var_name}.slice(0, 1)}}"
- assert str(var[:1]) == f"{{{var._var_name}.slice(0, 1)}}"
- assert str(var[:]) == f"{{{var._var_name}.slice(0, undefined)}}"
-
-
-def test_dict_indexing():
- """Test that we can index into dict vars."""
- dct = BaseVar(_var_name="dct", _var_type=Dict[str, int])
-
- # Check correct indexing.
- assert str(dct["a"]) == '{dct["a"]}'
- assert str(dct["asdf"]) == '{dct["asdf"]}'
-
-
-@pytest.mark.parametrize(
- "var, index",
- [
- (
- BaseVar(_var_name="dict", _var_type=Dict[str, str]),
- [1, 2],
- ),
- (
- BaseVar(_var_name="dict", _var_type=Dict[str, str]),
- {"name": "dict"},
- ),
- (
- BaseVar(_var_name="dict", _var_type=Dict[str, str]),
- {"set"},
- ),
- (
- BaseVar(_var_name="dict", _var_type=Dict[str, str]),
- (
- 1,
- 2,
- ),
- ),
- (
- BaseVar(_var_name="lst", _var_type=Dict[str, str]),
- BaseVar(_var_name="list_var", _var_type=List[int]),
- ),
- (
- BaseVar(_var_name="lst", _var_type=Dict[str, str]),
- BaseVar(_var_name="set_var", _var_type=Set[str]),
- ),
- (
- BaseVar(_var_name="lst", _var_type=Dict[str, str]),
- BaseVar(_var_name="dict_var", _var_type=Dict[str, str]),
- ),
- (
- BaseVar(_var_name="df", _var_type=DataFrame),
- [1, 2],
- ),
- (
- BaseVar(_var_name="df", _var_type=DataFrame),
- {"name": "dict"},
- ),
- (
- BaseVar(_var_name="df", _var_type=DataFrame),
- {"set"},
- ),
- (
- BaseVar(_var_name="df", _var_type=DataFrame),
- (
- 1,
- 2,
- ),
- ),
- (
- BaseVar(_var_name="df", _var_type=DataFrame),
- BaseVar(_var_name="list_var", _var_type=List[int]),
- ),
- (
- BaseVar(_var_name="df", _var_type=DataFrame),
- BaseVar(_var_name="set_var", _var_type=Set[str]),
- ),
- (
- BaseVar(_var_name="df", _var_type=DataFrame),
- BaseVar(_var_name="dict_var", _var_type=Dict[str, str]),
- ),
- ],
-)
-def test_var_unsupported_indexing_dicts(var, index):
- """Test unsupported indexing throws a type error.
-
- Args:
- var: The base var.
- index: The base var index.
- """
- with pytest.raises(TypeError):
- var[index]
-
-
-@pytest.mark.parametrize(
- "fixture,full_name",
- [
- ("ParentState", "parent_state.var_without_annotation"),
- ("ChildState", "parent_state__child_state.var_without_annotation"),
- (
- "GrandChildState",
- "parent_state__child_state__grand_child_state.var_without_annotation",
- ),
- ("StateWithAnyVar", "state_with_any_var.var_without_annotation"),
- ],
-)
-def test_computed_var_without_annotation_error(request, fixture, full_name):
- """Test that a type error is thrown when an attribute of a computed var is
- accessed without annotating the computed var.
-
- Args:
- request: Fixture Request.
- fixture: The state fixture.
- full_name: The full name of the state var.
- """
- with pytest.raises(TypeError) as err:
- state = request.getfixturevalue(fixture)
- state.var_without_annotation.foo
- assert (
- err.value.args[0]
- == f"You must provide an annotation for the state var `{full_name}`. Annotation cannot be `typing.Any`"
- )
-
-
-@pytest.mark.parametrize(
- "fixture,full_name",
- [
- (
- "StateWithCorrectVarAnnotation",
- "state_with_correct_var_annotation.var_with_annotation",
- ),
- (
- "StateWithWrongVarAnnotation",
- "state_with_wrong_var_annotation.var_with_annotation",
- ),
- ],
-)
-def test_computed_var_with_annotation_error(request, fixture, full_name):
- """Test that an Attribute error is thrown when a non-existent attribute of an annotated computed var is
- accessed or when the wrong annotation is provided to a computed var.
-
- Args:
- request: Fixture Request.
- fixture: The state fixture.
- full_name: The full name of the state var.
- """
- with pytest.raises(AttributeError) as err:
- state = request.getfixturevalue(fixture)
- state.var_with_annotation.foo
- assert (
- err.value.args[0]
- == f"The State var `{full_name}` has no attribute 'foo' or may have been annotated wrongly."
- )
-
-
-@pytest.mark.parametrize(
- "fixture,var_name,expected_initial,expected_runtime,raises_at_runtime",
- [
- (
- "StateWithInitialComputedVar",
- "var_with_initial_value",
- "Initial value",
- "Runtime value",
- False,
- ),
- (
- "ChildWithInitialComputedVar",
- "var_with_initial_value_child",
- "Initial value",
- "Runtime value",
- False,
- ),
- (
- "StateWithRuntimeOnlyVar",
- "var_raises_at_runtime",
- None,
- None,
- True,
- ),
- (
- "ChildWithRuntimeOnlyVar",
- "var_raises_at_runtime_child",
- "Initial value",
- None,
- True,
- ),
- ],
-)
-def test_state_with_initial_computed_var(
- request, fixture, var_name, expected_initial, expected_runtime, raises_at_runtime
-):
- """Test that the initial and runtime values of a computed var are correct.
-
- Args:
- request: Fixture Request.
- fixture: The state fixture.
- var_name: The name of the computed var.
- expected_initial: The expected initial value of the computed var.
- expected_runtime: The expected runtime value of the computed var.
- raises_at_runtime: Whether the computed var is runtime only.
- """
- state = request.getfixturevalue(fixture)()
- state_name = state.get_full_name()
- initial_dict = state.dict(initial=True)[state_name]
- assert initial_dict[var_name] == expected_initial
-
- if raises_at_runtime:
- with pytest.raises(ValueError):
- state.dict()[state_name][var_name]
- else:
- runtime_dict = state.dict()[state_name]
- assert runtime_dict[var_name] == expected_runtime
-
-
-@pytest.mark.parametrize(
- "out, expected",
- [
- (f"{BaseVar(_var_name='var', _var_type=str)}", "${var}"),
- (
- f"testing f-string with {BaseVar(_var_name='myvar', _var_type=int)._var_set_state('state')}",
- 'testing f-string with $
{"state": "state", "interpolations": [], "imports": {"/utils/context": [{"tag": "StateContexts", "is_default": false, "alias": null, "install": true, "render": true, "transpile": false}], "react": [{"tag": "useContext", "is_default": false, "alias": null, "install": true, "render": true, "transpile": false}]}, "hooks": {"const state = useContext(StateContexts.state)": null}, "string_length": 13} {state.myvar}',
- ),
- (
- f"testing local f-string {BaseVar(_var_name='x', _var_is_local=True, _var_type=str)}",
- "testing local f-string x",
- ),
- ],
-)
-def test_fstrings(out, expected):
- assert out == expected
-
-
-@pytest.mark.parametrize(
- ("value", "expect_state"),
- [
- ([1], ""),
- ({"a": 1}, ""),
- ([Var.create_safe(1)._var_set_state("foo")], "foo"),
- ({"a": Var.create_safe(1)._var_set_state("foo")}, "foo"),
- ],
-)
-def test_extract_state_from_container(value, expect_state):
- """Test that _var_state is extracted from containers containing BaseVar.
-
- Args:
- value: The value to create a var from.
- expect_state: The expected state.
- """
- assert Var.create_safe(value)._var_state == expect_state
-
-
-@pytest.mark.parametrize(
- "value",
- [
- "var",
- "\nvar",
- ],
-)
-def test_fstring_roundtrip(value):
- """Test that f-string roundtrip carries state.
-
- Args:
- value: The value to create a Var from.
- """
- var = BaseVar.create_safe(value)._var_set_state("state")
- rt_var = Var.create_safe(f"{var}")
- assert var._var_state == rt_var._var_state
- assert var._var_full_name_needs_state_prefix
- assert not rt_var._var_full_name_needs_state_prefix
- assert rt_var._var_name == var._var_full_name
-
-
-@pytest.mark.parametrize(
- "var",
- [
- BaseVar(_var_name="var", _var_type=int),
- BaseVar(_var_name="var", _var_type=float),
- BaseVar(_var_name="var", _var_type=str),
- BaseVar(_var_name="var", _var_type=bool),
- BaseVar(_var_name="var", _var_type=dict),
- BaseVar(_var_name="var", _var_type=tuple),
- BaseVar(_var_name="var", _var_type=set),
- BaseVar(_var_name="var", _var_type=None),
- ],
-)
-def test_unsupported_types_for_reverse(var):
- """Test that unsupported types for reverse throw a type error.
-
- Args:
- var: The base var.
- """
- with pytest.raises(TypeError) as err:
- var.reverse()
- assert err.value.args[0] == f"Cannot reverse non-list var var."
-
-
-@pytest.mark.parametrize(
- "var",
- [
- BaseVar(_var_name="var", _var_type=int),
- BaseVar(_var_name="var", _var_type=float),
- BaseVar(_var_name="var", _var_type=bool),
- BaseVar(_var_name="var", _var_type=None),
- ],
-)
-def test_unsupported_types_for_contains(var):
- """Test that unsupported types for contains throw a type error.
-
- Args:
- var: The base var.
- """
- with pytest.raises(TypeError) as err:
- assert var.contains(1)
- assert (
- err.value.args[0]
- == f"Var var of type {var._var_type} does not support contains check."
- )
-
-
-@pytest.mark.parametrize(
- "other",
- [
- BaseVar(_var_name="other", _var_type=int),
- BaseVar(_var_name="other", _var_type=float),
- BaseVar(_var_name="other", _var_type=bool),
- BaseVar(_var_name="other", _var_type=list),
- BaseVar(_var_name="other", _var_type=dict),
- BaseVar(_var_name="other", _var_type=tuple),
- BaseVar(_var_name="other", _var_type=set),
- ],
-)
-def test_unsupported_types_for_string_contains(other):
- with pytest.raises(TypeError) as err:
- assert BaseVar(_var_name="var", _var_type=str).contains(other)
- assert (
- err.value.args[0]
- == f"'in
' requires string as left operand, not {other._var_type}"
- )
-
-
-def test_unsupported_default_contains():
- with pytest.raises(TypeError) as err:
- assert 1 in BaseVar(_var_name="var", _var_type=str)
- assert (
- err.value.args[0]
- == "'in' operator not supported for Var types, use Var.contains() instead."
- )
-
-
-@pytest.mark.parametrize(
- "operand1_var,operand2_var,operators",
- [
- (
- Var.create(10),
- Var.create(5),
- [
- "+",
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "&",
- ],
- ),
- (
- Var.create(10.5),
- Var.create(5),
- ["+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="],
- ),
- (
- Var.create(5),
- Var.create(True),
- [
- "+",
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "&",
- ],
- ),
- (
- Var.create(10.5),
- Var.create(5.5),
- ["+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="],
- ),
- (
- Var.create(10.5),
- Var.create(True),
- ["+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="],
- ),
- (Var.create("10"), Var.create("5"), ["+", ">", "<", "<=", ">="]),
- (Var.create([10, 20]), Var.create([5, 6]), ["+", ">", "<", "<=", ">="]),
- (Var.create([10, 20]), Var.create(5), ["*"]),
- (Var.create([10, 20]), Var.create(True), ["*"]),
- (
- Var.create(True),
- Var.create(True),
- [
- "+",
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "&",
- ],
- ),
- ],
-)
-def test_valid_var_operations(operand1_var: Var, operand2_var, operators: List[str]):
- """Test that operations do not raise a TypeError.
-
- Args:
- operand1_var: left operand.
- operand2_var: right operand.
- operators: list of supported operators.
- """
- for operator in operators:
- operand1_var.operation(op=operator, other=operand2_var)
- operand1_var.operation(op=operator, other=operand2_var, flip=True)
-
-
-@pytest.mark.parametrize(
- "operand1_var,operand2_var,operators",
- [
- (
- Var.create(10),
- Var.create(5),
- [
- "^",
- "<<",
- ">>",
- ],
- ),
- (
- Var.create(10.5),
- Var.create(5),
- [
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create(10.5),
- Var.create(True),
- [
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create(10.5),
- Var.create(5.5),
- [
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create("10"),
- Var.create("5"),
- [
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create([10, 20]),
- Var.create([5, 6]),
- [
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create([10, 20]),
- Var.create(5),
- [
- "+",
- "-",
- "/",
- "//",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create([10, 20]),
- Var.create(True),
- [
- "+",
- "-",
- "/",
- "//",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create([10, 20]),
- Var.create("5"),
- [
- "+",
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create([10, 20]),
- Var.create({"key": "value"}),
- [
- "+",
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create([10, 20]),
- Var.create(5.5),
- [
- "+",
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create({"key": "value"}),
- Var.create({"another_key": "another_value"}),
- [
- "+",
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create({"key": "value"}),
- Var.create(5),
- [
- "+",
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create({"key": "value"}),
- Var.create(True),
- [
- "+",
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create({"key": "value"}),
- Var.create(5.5),
- [
- "+",
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create({"key": "value"}),
- Var.create("5"),
- [
- "+",
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- ],
-)
-def test_invalid_var_operations(operand1_var: Var, operand2_var, operators: List[str]):
- for operator in operators:
- with pytest.raises(TypeError):
- operand1_var.operation(op=operator, other=operand2_var)
-
- with pytest.raises(TypeError):
- operand1_var.operation(op=operator, other=operand2_var, flip=True)
-
-
-@pytest.mark.parametrize(
- "var, expected",
- [
- (Var.create("string_value", _var_is_string=True), "`string_value`"),
- (Var.create(1), "1"),
- (Var.create([1, 2, 3]), "[1, 2, 3]"),
- (Var.create({"foo": "bar"}), '{"foo": "bar"}'),
- (Var.create(ATestState.value, _var_is_string=True), "a_test_state.value"),
- (
- Var.create(f"{ATestState.value} string", _var_is_string=True),
- "`${a_test_state.value} string`",
- ),
- (Var.create(ATestState.dict_val), "a_test_state.dict_val"),
- ],
-)
-def test_var_name_unwrapped(var, expected):
- assert var._var_name_unwrapped == expected
diff --git a/tests/units/__init__.py b/tests/units/__init__.py
new file mode 100644
index 000000000..d0196603c
--- /dev/null
+++ b/tests/units/__init__.py
@@ -0,0 +1,5 @@
+"""Root directory for tests."""
+
+import os
+
+from reflex import constants
diff --git a/tests/compiler/__init__.py b/tests/units/compiler/__init__.py
similarity index 100%
rename from tests/compiler/__init__.py
rename to tests/units/compiler/__init__.py
diff --git a/tests/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py
similarity index 94%
rename from tests/compiler/test_compiler.py
rename to tests/units/compiler/test_compiler.py
index b6191974a..afacf43c5 100644
--- a/tests/compiler/test_compiler.py
+++ b/tests/units/compiler/test_compiler.py
@@ -1,11 +1,10 @@
-import os
+from pathlib import Path
from typing import List
import pytest
from reflex.compiler import compiler, utils
-from reflex.utils import imports
-from reflex.utils.imports import ImportVar
+from reflex.utils.imports import ImportVar, ParsedImportDict
@pytest.mark.parametrize(
@@ -93,7 +92,7 @@ def test_compile_import_statement(
),
],
)
-def test_compile_imports(import_dict: imports.ImportDict, test_dicts: List[dict]):
+def test_compile_imports(import_dict: ParsedImportDict, test_dicts: List[dict]):
"""Test the compile_imports function.
Args:
@@ -131,11 +130,11 @@ def test_compile_stylesheets(tmp_path, mocker):
]
assert compiler.compile_root_stylesheet(stylesheets) == (
- os.path.join(".web", "styles", "styles.css"),
+ str(Path(".web") / "styles" / "styles.css"),
f"@import url('./tailwind.css'); \n"
f"@import url('https://fonts.googleapis.com/css?family=Sofia&effect=neon|outline|emboss|shadow-multiple'); \n"
f"@import url('https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css'); \n"
- f"@import url('@/styles.css'); \n"
+ f"@import url('../public/styles.css'); \n"
f"@import url('https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap-theme.min.css'); \n",
)
@@ -165,8 +164,8 @@ def test_compile_stylesheets_exclude_tailwind(tmp_path, mocker):
]
assert compiler.compile_root_stylesheet(stylesheets) == (
- os.path.join(".web", "styles", "styles.css"),
- "@import url('@/styles.css'); \n",
+ str(Path(".web") / "styles" / "styles.css"),
+ "@import url('../public/styles.css'); \n",
)
diff --git a/tests/compiler/test_compiler_utils.py b/tests/units/compiler/test_compiler_utils.py
similarity index 100%
rename from tests/compiler/test_compiler_utils.py
rename to tests/units/compiler/test_compiler_utils.py
diff --git a/tests/components/__init__.py b/tests/units/components/__init__.py
similarity index 100%
rename from tests/components/__init__.py
rename to tests/units/components/__init__.py
diff --git a/tests/components/base/test_bare.py b/tests/units/components/base/test_bare.py
similarity index 53%
rename from tests/components/base/test_bare.py
rename to tests/units/components/base/test_bare.py
index 264d136cb..c30ffaf15 100644
--- a/tests/components/base/test_bare.py
+++ b/tests/units/components/base/test_bare.py
@@ -1,16 +1,21 @@
import pytest
from reflex.components.base.bare import Bare
+from reflex.vars.base import Var
+
+STATE_VAR = Var(_js_expr="default_state.name")
@pytest.mark.parametrize(
"contents,expected",
[
- ("hello", "hello"),
- ("{}", "{}"),
- (None, ""),
- ("${default_state.name}", "${default_state.name}"),
- ("{state.name}", "{state.name}"),
+ ("hello", '{"hello"}'),
+ ("{}", '{"{}"}'),
+ (None, '{""}'),
+ (STATE_VAR, "{default_state.name}"),
+ # This behavior is now unsupported.
+ # ("${default_state.name}", "${default_state.name}"),
+ # ("{state.name}", "{state.name}"),
],
)
def test_fstrings(contents, expected):
diff --git a/tests/units/components/base/test_link.py b/tests/units/components/base/test_link.py
new file mode 100644
index 000000000..7713330c4
--- /dev/null
+++ b/tests/units/components/base/test_link.py
@@ -0,0 +1,15 @@
+from reflex.components.base.link import RawLink, ScriptTag
+
+
+def test_raw_link():
+ raw_link = RawLink.create("https://example.com").render()
+ assert raw_link["name"] == "link"
+ assert raw_link["children"][0]["contents"] == '{"https://example.com"}'
+
+
+def test_script_tag():
+ script_tag = ScriptTag.create("console.log('Hello, world!');").render()
+ assert script_tag["name"] == "script"
+ assert (
+ script_tag["children"][0]["contents"] == "{\"console.log('Hello, world!');\"}"
+ )
diff --git a/tests/components/base/test_script.py b/tests/units/components/base/test_script.py
similarity index 73%
rename from tests/components/base/test_script.py
rename to tests/units/components/base/test_script.py
index 7ccdc0634..b909b6c61 100644
--- a/tests/components/base/test_script.py
+++ b/tests/units/components/base/test_script.py
@@ -1,6 +1,8 @@
"""Test that Script from next/script renders correctly."""
+
import pytest
+import reflex as rx
from reflex.components.base.script import Script
from reflex.state import BaseState
@@ -12,7 +14,7 @@ def test_script_inline():
assert render_dict["name"] == "Script"
assert not render_dict["contents"]
assert len(render_dict["children"]) == 1
- assert render_dict["children"][0]["contents"] == "{`let x = 42`}"
+ assert render_dict["children"][0]["contents"] == '{"let x = 42"}'
def test_script_src():
@@ -22,7 +24,7 @@ def test_script_src():
assert render_dict["name"] == "Script"
assert not render_dict["contents"]
assert not render_dict["children"]
- assert "src={`foo.js`}" in render_dict["props"]
+ assert 'src={"foo.js"}' in render_dict["props"]
def test_script_neither():
@@ -34,14 +36,17 @@ def test_script_neither():
class EvState(BaseState):
"""State for testing event handlers."""
+ @rx.event
def on_ready(self):
"""Empty event handler."""
pass
+ @rx.event
def on_load(self):
"""Empty event handler."""
pass
+ @rx.event
def on_error(self):
"""Empty event handler."""
pass
@@ -57,14 +62,14 @@ def test_script_event_handler():
)
render_dict = component.render()
assert (
- 'onReady={(_e) => addEvents([Event("ev_state.on_ready", {})], (_e), {})}'
+ f'onReady={{((...args) => ((addEvents([(Event("{EvState.get_full_name()}.on_ready", ({{ }}), ({{ }})))], args, ({{ }})))))}}'
in render_dict["props"]
)
assert (
- 'onLoad={(_e) => addEvents([Event("ev_state.on_load", {})], (_e), {})}'
+ f'onLoad={{((...args) => ((addEvents([(Event("{EvState.get_full_name()}.on_load", ({{ }}), ({{ }})))], args, ({{ }})))))}}'
in render_dict["props"]
)
assert (
- 'onError={(_e) => addEvents([Event("ev_state.on_error", {})], (_e), {})}'
+ f'onError={{((...args) => ((addEvents([(Event("{EvState.get_full_name()}.on_error", ({{ }}), ({{ }})))], args, ({{ }})))))}}'
in render_dict["props"]
)
diff --git a/reflex/.templates/apps/demo/code/webui/__init__.py b/tests/units/components/core/__init__.py
similarity index 100%
rename from reflex/.templates/apps/demo/code/webui/__init__.py
rename to tests/units/components/core/__init__.py
diff --git a/tests/components/core/test_banner.py b/tests/units/components/core/test_banner.py
similarity index 60%
rename from tests/components/core/test_banner.py
rename to tests/units/components/core/test_banner.py
index f929eef37..7add913ea 100644
--- a/tests/components/core/test_banner.py
+++ b/tests/units/components/core/test_banner.py
@@ -9,20 +9,25 @@ from reflex.components.radix.themes.typography.text import Text
def test_websocket_target_url():
url = WebsocketTargetURL.create()
- _imports = url._get_all_imports(collapse=True)
- assert list(_imports.keys()) == ["/utils/state", "/env.json"]
+ var_data = url._get_all_var_data()
+ assert var_data is not None
+ assert sorted(tuple((key for key, _ in var_data.imports))) == sorted(
+ ("$/utils/state", "$/env.json")
+ )
def test_connection_banner():
banner = ConnectionBanner.create()
_imports = banner._get_all_imports(collapse=True)
- assert list(_imports.keys()) == [
- "react",
- "/utils/context",
- "/utils/state",
- "@radix-ui/themes@^3.0.0",
- "/env.json",
- ]
+ assert sorted(tuple(_imports)) == sorted(
+ (
+ "react",
+ "$/utils/context",
+ "$/utils/state",
+ "@radix-ui/themes@^3.0.0",
+ "$/env.json",
+ )
+ )
msg = "Connection error"
custom_banner = ConnectionBanner.create(Text.create(msg))
@@ -32,13 +37,15 @@ def test_connection_banner():
def test_connection_modal():
modal = ConnectionModal.create()
_imports = modal._get_all_imports(collapse=True)
- assert list(_imports.keys()) == [
- "react",
- "/utils/context",
- "/utils/state",
- "@radix-ui/themes@^3.0.0",
- "/env.json",
- ]
+ assert sorted(tuple(_imports)) == sorted(
+ (
+ "react",
+ "$/utils/context",
+ "$/utils/state",
+ "@radix-ui/themes@^3.0.0",
+ "$/env.json",
+ )
+ )
msg = "Connection error"
custom_modal = ConnectionModal.create(Text.create(msg))
diff --git a/tests/units/components/core/test_colors.py b/tests/units/components/core/test_colors.py
new file mode 100644
index 000000000..74fbeb20f
--- /dev/null
+++ b/tests/units/components/core/test_colors.py
@@ -0,0 +1,136 @@
+from typing import Type, Union
+
+import pytest
+
+import reflex as rx
+from reflex.components.datadisplay.code import CodeBlock
+from reflex.constants.colors import Color
+from reflex.vars.base import LiteralVar
+
+
+class ColorState(rx.State):
+ """Test color state."""
+
+ color: str = "mint"
+ color_part: str = "tom"
+ shade: int = 4
+ alpha: bool = False
+
+
+color_state_name = ColorState.get_full_name().replace(".", "__")
+
+
+def create_color_var(color):
+ return LiteralVar.create(color)
+
+
+@pytest.mark.parametrize(
+ "color, expected, expected_type",
+ [
+ (create_color_var(rx.color("mint")), '"var(--mint-7)"', Color),
+ (create_color_var(rx.color("mint", 3)), '"var(--mint-3)"', Color),
+ (create_color_var(rx.color("mint", 3, True)), '"var(--mint-a3)"', Color),
+ (
+ create_color_var(rx.color(ColorState.color, ColorState.shade)), # type: ignore
+ f'("var(--"+{str(color_state_name)}.color+"-"+(((__to_string) => __to_string.toString())({str(color_state_name)}.shade))+")")',
+ Color,
+ ),
+ (
+ create_color_var(
+ rx.color(ColorState.color, ColorState.shade, ColorState.alpha) # type: ignore
+ ),
+ f'("var(--"+{str(color_state_name)}.color+"-"+({str(color_state_name)}.alpha ? "a" : "")+(((__to_string) => __to_string.toString())({str(color_state_name)}.shade))+")")',
+ Color,
+ ),
+ (
+ create_color_var(rx.color(f"{ColorState.color}", f"{ColorState.shade}")), # type: ignore
+ f'("var(--"+{str(color_state_name)}.color+"-"+{str(color_state_name)}.shade+")")',
+ Color,
+ ),
+ (
+ create_color_var(
+ rx.color(f"{ColorState.color_part}ato", f"{ColorState.shade}") # type: ignore
+ ),
+ f'("var(--"+({str(color_state_name)}.color_part+"ato")+"-"+{str(color_state_name)}.shade+")")',
+ Color,
+ ),
+ (
+ create_color_var(f'{rx.color(ColorState.color, f"{ColorState.shade}")}'), # type: ignore
+ f'("var(--"+{str(color_state_name)}.color+"-"+{str(color_state_name)}.shade+")")',
+ str,
+ ),
+ (
+ create_color_var(
+ f'{rx.color(f"{ColorState.color}", f"{ColorState.shade}")}' # type: ignore
+ ),
+ f'("var(--"+{str(color_state_name)}.color+"-"+{str(color_state_name)}.shade+")")',
+ str,
+ ),
+ ],
+)
+def test_color(color, expected, expected_type: Union[Type[str], Type[Color]]):
+ assert color._var_type is expected_type
+ assert str(color) == expected
+
+
+@pytest.mark.parametrize(
+ "cond_var, expected",
+ [
+ (
+ rx.cond(True, rx.color("mint"), rx.color("tomato", 5)),
+ '(true ? "var(--mint-7)" : "var(--tomato-5)")',
+ ),
+ (
+ rx.cond(True, rx.color(ColorState.color), rx.color(ColorState.color, 5)), # type: ignore
+ f'(true ? ("var(--"+{str(color_state_name)}.color+"-7)") : ("var(--"+{str(color_state_name)}.color+"-5)"))',
+ ),
+ (
+ rx.match(
+ "condition",
+ ("first", rx.color("mint")),
+ ("second", rx.color("tomato", 5)),
+ rx.color(ColorState.color, 2), # type: ignore
+ ),
+ '(() => { switch (JSON.stringify("condition")) {case JSON.stringify("first"): return ("var(--mint-7)");'
+ ' break;case JSON.stringify("second"): return ("var(--tomato-5)"); break;default: '
+ f'return (("var(--"+{str(color_state_name)}.color+"-2)")); break;}};}})()',
+ ),
+ (
+ rx.match(
+ "condition",
+ ("first", rx.color(ColorState.color)), # type: ignore
+ ("second", rx.color(ColorState.color, 5)), # type: ignore
+ rx.color(ColorState.color, 2), # type: ignore
+ ),
+ '(() => { switch (JSON.stringify("condition")) {case JSON.stringify("first"): '
+ f'return (("var(--"+{str(color_state_name)}.color+"-7)")); break;case JSON.stringify("second"): '
+ f'return (("var(--"+{str(color_state_name)}.color+"-5)")); break;default: '
+ f'return (("var(--"+{str(color_state_name)}.color+"-2)")); break;}};}})()',
+ ),
+ ],
+)
+def test_color_with_conditionals(cond_var, expected):
+ assert str(cond_var) == expected
+
+
+@pytest.mark.parametrize(
+ "color, expected",
+ [
+ (create_color_var(rx.color("red")), '"var(--red-7)"'),
+ (create_color_var(rx.color("green", shade=1)), '"var(--green-1)"'),
+ (create_color_var(rx.color("blue", alpha=True)), '"var(--blue-a7)"'),
+ ("red", '"red"'),
+ ("green", '"green"'),
+ ("blue", '"blue"'),
+ ],
+)
+def test_radix_color(color, expected):
+ """Test that custom_style can accept both string
+ literals and rx.color inputs.
+
+ Args:
+ color (Color): A Color made with rx.color
+ expected (str): The expected custom_style string, radix or literal
+ """
+ code_block = CodeBlock.create("Hello World", background_color=color)
+ assert str(code_block.custom_style["backgroundColor"]) == expected # type: ignore
diff --git a/tests/components/core/test_cond.py b/tests/units/components/core/test_cond.py
similarity index 65%
rename from tests/components/core/test_cond.py
rename to tests/units/components/core/test_cond.py
index a7604fb9a..f9bdc7d60 100644
--- a/tests/components/core/test_cond.py
+++ b/tests/units/components/core/test_cond.py
@@ -1,5 +1,5 @@
import json
-from typing import Any
+from typing import Any, Union
import pytest
@@ -7,7 +7,8 @@ from reflex.components.base.fragment import Fragment
from reflex.components.core.cond import Cond, cond
from reflex.components.radix.themes.typography.text import Text
from reflex.state import BaseState
-from reflex.vars import Var
+from reflex.utils.format import format_state_name
+from reflex.vars.base import LiteralVar, Var, computed_var
@pytest.fixture
@@ -20,8 +21,8 @@ def cond_state(request):
def test_f_string_cond_interpolation():
# make sure backticks inside interpolation don't get escaped
- var = Var.create(f"x {cond(True, 'a', 'b')}")
- assert str(var) == "x ${isTrue(true) ? `a` : `b`}"
+ var = LiteralVar.create(f"x {cond(True, 'a', 'b')}")
+ assert str(var) == '("x "+(true ? "a" : "b"))'
@pytest.mark.parametrize(
@@ -33,7 +34,7 @@ def test_f_string_cond_interpolation():
],
indirect=True,
)
-def test_validate_cond(cond_state: Var):
+def test_validate_cond(cond_state: BaseState):
"""Test if cond can be a rx.Var with any values.
Args:
@@ -44,11 +45,11 @@ def test_validate_cond(cond_state: Var):
Text.create("cond is True"),
Text.create("cond is False"),
)
- cond_dict = cond_component.render() if type(cond_component) == Fragment else {}
+ cond_dict = cond_component.render() if type(cond_component) is Fragment else {}
assert cond_dict["name"] == "Fragment"
[condition] = cond_dict["children"]
- assert condition["cond_state"] == "isTrue(cond_state.value)"
+ assert condition["cond_state"] == f"isTrue({cond_state.get_full_name()}.value)"
# true value
true_value = condition["true_value"]
@@ -56,7 +57,7 @@ def test_validate_cond(cond_state: Var):
[true_value_text] = true_value["children"]
assert true_value_text["name"] == "RadixThemesText"
- assert true_value_text["children"][0]["contents"] == "{`cond is True`}"
+ assert true_value_text["children"][0]["contents"] == '{"cond is True"}'
# false value
false_value = condition["false_value"]
@@ -64,7 +65,7 @@ def test_validate_cond(cond_state: Var):
[false_value_text] = false_value["children"]
assert false_value_text["name"] == "RadixThemesText"
- assert false_value_text["children"][0]["contents"] == "{`cond is False`}"
+ assert false_value_text["children"][0]["contents"] == '{"cond is False"}'
@pytest.mark.parametrize(
@@ -74,7 +75,7 @@ def test_validate_cond(cond_state: Var):
(32, 0),
("hello", ""),
(2.3, 0.0),
- (Var.create("a"), Var.create("b")),
+ (LiteralVar.create("a"), LiteralVar.create("b")),
],
)
def test_prop_cond(c1: Any, c2: Any):
@@ -92,16 +93,16 @@ def test_prop_cond(c1: Any, c2: Any):
assert isinstance(prop_cond, Var)
if not isinstance(c1, Var):
- c1 = json.dumps(c1).replace('"', "`")
+ c1 = json.dumps(c1)
if not isinstance(c2, Var):
- c2 = json.dumps(c2).replace('"', "`")
- assert str(prop_cond) == f"{{isTrue(true) ? {c1} : {c2}}}"
+ c2 = json.dumps(c2)
+ assert str(prop_cond) == f"(true ? {str(c1)} : {str(c2)})"
def test_cond_no_mix():
"""Test if cond can't mix components and props."""
with pytest.raises(ValueError):
- cond(True, Var.create("hello"), Text.create("world"))
+ cond(True, LiteralVar.create("hello"), Text.create("world"))
def test_cond_no_else():
@@ -118,3 +119,28 @@ def test_cond_no_else():
# Props do not support the use of cond without else
with pytest.raises(ValueError):
cond(True, "hello") # type: ignore
+
+
+def test_cond_computed_var():
+ """Test if cond works with computed vars."""
+
+ class CondStateComputed(BaseState):
+ @computed_var
+ def computed_int(self) -> int:
+ return 0
+
+ @computed_var
+ def computed_str(self) -> str:
+ return "a string"
+
+ comp = cond(True, CondStateComputed.computed_int, CondStateComputed.computed_str)
+
+ # TODO: shouln't this be a ComputedVar?
+ assert isinstance(comp, Var)
+
+ state_name = format_state_name(CondStateComputed.get_full_name())
+ assert (
+ str(comp) == f"(true ? {state_name}.computed_int : {state_name}.computed_str)"
+ )
+
+ assert comp._var_type == Union[int, str]
diff --git a/tests/components/core/test_debounce.py b/tests/units/components/core/test_debounce.py
similarity index 75%
rename from tests/components/core/test_debounce.py
rename to tests/units/components/core/test_debounce.py
index 8a8ec394c..7856ee090 100644
--- a/tests/components/core/test_debounce.py
+++ b/tests/units/components/core/test_debounce.py
@@ -5,7 +5,7 @@ import pytest
import reflex as rx
from reflex.components.core.debounce import DEFAULT_DEBOUNCE_TIMEOUT
from reflex.state import BaseState
-from reflex.vars import BaseVar
+from reflex.vars.base import LiteralVar, Var
def test_create_no_child():
@@ -37,6 +37,7 @@ class S(BaseState):
value: str = ""
+ @rx.event
def on_change(self, v: str):
"""Dummy on_change handler.
@@ -57,14 +58,10 @@ def test_render_child_props():
on_change=S.on_change,
)
)._render()
- assert "css" in tag.props and isinstance(tag.props["css"], rx.Var)
+ assert "css" in tag.props and isinstance(tag.props["css"], rx.vars.Var)
for prop in ["foo", "bar", "baz", "quuc"]:
assert prop in str(tag.props["css"])
- assert tag.props["value"].equals(
- BaseVar(
- _var_name="real", _var_type=str, _var_is_local=True, _var_is_string=False
- )
- )
+ assert tag.props["value"].equals(LiteralVar.create("real"))
assert len(tag.props["onChange"].events) == 1
assert tag.props["onChange"].events[0].handler == S.on_change
assert tag.contents == ""
@@ -77,7 +74,7 @@ def test_render_with_class_name():
class_name="foo baz",
)
)._render()
- assert isinstance(tag.props["className"], rx.Var)
+ assert isinstance(tag.props["className"], rx.vars.Var)
assert "foo baz" in str(tag.props["className"])
@@ -88,21 +85,43 @@ def test_render_with_ref():
id="foo_bar",
)
)._render()
- assert isinstance(tag.props["inputRef"], rx.Var)
+ assert isinstance(tag.props["inputRef"], rx.vars.Var)
assert "foo_bar" in str(tag.props["inputRef"])
+def test_render_with_key():
+ tag = rx.debounce_input(
+ rx.input(
+ on_change=S.on_change,
+ key="foo_bar",
+ )
+ )._render()
+ assert isinstance(tag.props["key"], rx.vars.Var)
+ assert "foo_bar" in str(tag.props["key"])
+
+
+def test_render_with_special_props():
+ special_prop = Var(_js_expr="{foo_bar}")
+ tag = rx.debounce_input(
+ rx.input(
+ on_change=S.on_change,
+ special_props=[special_prop],
+ )
+ )._render()
+ assert len(tag.special_props) == 1
+ assert list(tag.special_props)[0].equals(special_prop)
+
+
def test_event_triggers():
debounced_input = rx.debounce_input(
rx.input(
on_change=S.on_change,
)
)
- default_event_triggers = list(rx.Component().get_event_triggers().keys())
- assert list(debounced_input.get_event_triggers().keys()) == [
- *default_event_triggers,
+ assert tuple(debounced_input.get_event_triggers()) == (
+ *rx.Component().get_event_triggers(), # default event triggers
"on_change",
- ]
+ )
def test_render_child_props_recursive():
@@ -131,17 +150,13 @@ def test_render_child_props_recursive():
),
force_notify_by_enter=False,
)._render()
- assert "css" in tag.props and isinstance(tag.props["css"], rx.Var)
+ assert "css" in tag.props and isinstance(tag.props["css"], rx.vars.Var)
for prop in ["foo", "bar", "baz", "quuc"]:
assert prop in str(tag.props["css"])
- assert tag.props["value"].equals(
- BaseVar(
- _var_name="outer", _var_type=str, _var_is_local=True, _var_is_string=False
- )
- )
- assert tag.props["forceNotifyOnBlur"]._var_name == "false"
- assert tag.props["forceNotifyByEnter"]._var_name == "false"
- assert tag.props["debounceTimeout"]._var_name == "42"
+ assert tag.props["value"].equals(LiteralVar.create("outer"))
+ assert tag.props["forceNotifyOnBlur"]._js_expr == "false"
+ assert tag.props["forceNotifyByEnter"]._js_expr == "false"
+ assert tag.props["debounceTimeout"]._js_expr == "42"
assert len(tag.props["onChange"].events) == 1
assert tag.props["onChange"].events[0].handler == S.on_change
assert tag.contents == ""
@@ -153,7 +168,7 @@ def test_full_control_implicit_debounce():
value=S.value,
on_change=S.on_change,
)._render()
- assert tag.props["debounceTimeout"]._var_name == str(DEFAULT_DEBOUNCE_TIMEOUT)
+ assert tag.props["debounceTimeout"]._js_expr == str(DEFAULT_DEBOUNCE_TIMEOUT)
assert len(tag.props["onChange"].events) == 1
assert tag.props["onChange"].events[0].handler == S.on_change
assert tag.contents == ""
@@ -165,7 +180,7 @@ def test_full_control_implicit_debounce_text_area():
value=S.value,
on_change=S.on_change,
)._render()
- assert tag.props["debounceTimeout"]._var_name == str(DEFAULT_DEBOUNCE_TIMEOUT)
+ assert tag.props["debounceTimeout"]._js_expr == str(DEFAULT_DEBOUNCE_TIMEOUT)
assert len(tag.props["onChange"].events) == 1
assert tag.props["onChange"].events[0].handler == S.on_change
assert tag.contents == ""
diff --git a/tests/components/core/test_foreach.py b/tests/units/components/core/test_foreach.py
similarity index 71%
rename from tests/components/core/test_foreach.py
rename to tests/units/components/core/test_foreach.py
index 9691ed50e..228165d3e 100644
--- a/tests/components/core/test_foreach.py
+++ b/tests/units/components/core/test_foreach.py
@@ -2,10 +2,20 @@ from typing import Dict, List, Set, Tuple, Union
import pytest
-from reflex.components import box, el, foreach, text
-from reflex.components.core.foreach import Foreach, ForeachRenderError, ForeachVarError
-from reflex.state import BaseState
-from reflex.vars import Var
+from reflex import el
+from reflex.components.component import Component
+from reflex.components.core.foreach import (
+ Foreach,
+ ForeachRenderError,
+ ForeachVarError,
+ foreach,
+)
+from reflex.components.radix.themes.layout.box import box
+from reflex.components.radix.themes.typography.text import text
+from reflex.state import BaseState, ComponentState
+from reflex.vars.base import Var
+from reflex.vars.number import NumberVar
+from reflex.vars.sequence import ArrayVar
class ForEachState(BaseState):
@@ -37,8 +47,27 @@ class ForEachState(BaseState):
color_index_tuple: Tuple[int, str] = (0, "red")
+class ComponentStateTest(ComponentState):
+ """A test component state."""
+
+ foo: bool
+
+ @classmethod
+ def get_component(cls, *children, **props) -> Component:
+ """Get the component.
+
+ Args:
+ children: The children components.
+ props: The component props.
+
+ Returns:
+ The component.
+ """
+ return el.div(*children, **props)
+
+
def display_color(color):
- assert color._var_type == str
+ assert color._var_type is str
return box(text(color))
@@ -77,18 +106,18 @@ def display_nested_color_with_shades_v2(color):
def display_color_tuple(color):
- assert color._var_type == str
+ assert color._var_type is str
return box(text(color))
def display_colors_set(color):
- assert color._var_type == str
+ assert color._var_type is str
return box(text(color))
-def display_nested_list_element(element: Var[str], index: Var[int]):
+def display_nested_list_element(element: ArrayVar[List[str]], index: NumberVar[int]):
assert element._var_type == List[str]
- assert index._var_type == int
+ assert index._var_type is int
return box(text(element[index]))
@@ -107,7 +136,7 @@ seen_index_vars = set()
ForEachState.colors_list,
display_color,
{
- "iterable_state": "for_each_state.colors_list",
+ "iterable_state": f"{ForEachState.get_full_name()}.colors_list",
"iterable_type": "list",
},
),
@@ -115,7 +144,7 @@ seen_index_vars = set()
ForEachState.colors_dict_list,
display_color_name,
{
- "iterable_state": "for_each_state.colors_dict_list",
+ "iterable_state": f"{ForEachState.get_full_name()}.colors_dict_list",
"iterable_type": "list",
},
),
@@ -123,7 +152,7 @@ seen_index_vars = set()
ForEachState.colors_nested_dict_list,
display_shade,
{
- "iterable_state": "for_each_state.colors_nested_dict_list",
+ "iterable_state": f"{ForEachState.get_full_name()}.colors_nested_dict_list",
"iterable_type": "list",
},
),
@@ -131,7 +160,7 @@ seen_index_vars = set()
ForEachState.primary_color,
display_primary_colors,
{
- "iterable_state": "for_each_state.primary_color",
+ "iterable_state": f"{ForEachState.get_full_name()}.primary_color",
"iterable_type": "dict",
},
),
@@ -139,7 +168,7 @@ seen_index_vars = set()
ForEachState.color_with_shades,
display_color_with_shades,
{
- "iterable_state": "for_each_state.color_with_shades",
+ "iterable_state": f"{ForEachState.get_full_name()}.color_with_shades",
"iterable_type": "dict",
},
),
@@ -147,7 +176,7 @@ seen_index_vars = set()
ForEachState.nested_colors_with_shades,
display_nested_color_with_shades,
{
- "iterable_state": "for_each_state.nested_colors_with_shades",
+ "iterable_state": f"{ForEachState.get_full_name()}.nested_colors_with_shades",
"iterable_type": "dict",
},
),
@@ -155,7 +184,7 @@ seen_index_vars = set()
ForEachState.nested_colors_with_shades,
display_nested_color_with_shades_v2,
{
- "iterable_state": "for_each_state.nested_colors_with_shades",
+ "iterable_state": f"{ForEachState.get_full_name()}.nested_colors_with_shades",
"iterable_type": "dict",
},
),
@@ -163,7 +192,7 @@ seen_index_vars = set()
ForEachState.color_tuple,
display_color_tuple,
{
- "iterable_state": "for_each_state.color_tuple",
+ "iterable_state": f"{ForEachState.get_full_name()}.color_tuple",
"iterable_type": "tuple",
},
),
@@ -171,7 +200,7 @@ seen_index_vars = set()
ForEachState.colors_set,
display_colors_set,
{
- "iterable_state": "for_each_state.colors_set",
+ "iterable_state": f"{ForEachState.get_full_name()}.colors_set",
"iterable_type": "set",
},
),
@@ -179,7 +208,7 @@ seen_index_vars = set()
ForEachState.nested_colors_list,
lambda el, i: display_nested_list_element(el, i),
{
- "iterable_state": "for_each_state.nested_colors_list",
+ "iterable_state": f"{ForEachState.get_full_name()}.nested_colors_list",
"iterable_type": "list",
},
),
@@ -187,7 +216,7 @@ seen_index_vars = set()
ForEachState.color_index_tuple,
display_color_index_tuple,
{
- "iterable_state": "for_each_state.color_index_tuple",
+ "iterable_state": f"{ForEachState.get_full_name()}.color_index_tuple",
"iterable_type": "tuple",
},
),
@@ -210,9 +239,9 @@ def test_foreach_render(state_var, render_fn, render_dict):
# Make sure the index vars are unique.
arg_index = rend["arg_index"]
assert isinstance(arg_index, Var)
- assert arg_index._var_name not in seen_index_vars
- assert arg_index._var_type == int
- seen_index_vars.add(arg_index._var_name)
+ assert arg_index._js_expr not in seen_index_vars
+ assert arg_index._var_type is int
+ seen_index_vars.add(arg_index._js_expr)
def test_foreach_bad_annotations():
@@ -251,4 +280,13 @@ def test_foreach_component_styles():
)
)
component._add_style_recursive({box: {"color": "red"}})
- assert 'css={{"color": "red"}}' in str(component)
+ assert 'css={({ ["color"] : "red" })}' in str(component)
+
+
+def test_foreach_component_state():
+ """Test that using a component state to render in the foreach raises an error."""
+ with pytest.raises(TypeError):
+ Foreach.create(
+ ForEachState.colors_list,
+ ComponentStateTest.create,
+ )
diff --git a/tests/units/components/core/test_html.py b/tests/units/components/core/test_html.py
new file mode 100644
index 000000000..4847e1d5a
--- /dev/null
+++ b/tests/units/components/core/test_html.py
@@ -0,0 +1,41 @@
+import pytest
+
+from reflex.components.core.html import Html
+from reflex.state import State
+
+
+def test_html_no_children():
+ with pytest.raises(ValueError):
+ _ = Html.create()
+
+
+def test_html_many_children():
+ with pytest.raises(ValueError):
+ _ = Html.create("foo", "bar")
+
+
+def test_html_create():
+ html = Html.create("Hello !
")
+ assert str(html.dangerouslySetInnerHTML) == '({ ["__html"] : "Hello !
" })' # type: ignore
+ assert (
+ str(html)
+ == 'Hello !" })}/>'
+ )
+
+
+def test_html_fstring_create():
+ class TestState(State):
+ """The app state."""
+
+ myvar: str = "Blue"
+
+ html = Html.create(f"
Hello {TestState.myvar}!
")
+
+ assert (
+ str(html.dangerouslySetInnerHTML) # type: ignore
+ == f'({{ ["__html"] : ("
Hello "+{str(TestState.myvar)}+"!
") }})'
+ )
+ assert (
+ str(html)
+ == f'
' # type: ignore
+ )
diff --git a/tests/components/core/test_match.py b/tests/units/components/core/test_match.py
similarity index 71%
rename from tests/components/core/test_match.py
rename to tests/units/components/core/test_match.py
index 5a0e46e9e..f09e800e5 100644
--- a/tests/components/core/test_match.py
+++ b/tests/units/components/core/test_match.py
@@ -1,4 +1,4 @@
-from typing import Tuple
+from typing import Dict, List, Tuple
import pytest
@@ -6,7 +6,7 @@ import reflex as rx
from reflex.components.core.match import Match
from reflex.state import BaseState
from reflex.utils.exceptions import MatchTypeError
-from reflex.vars import BaseVar
+from reflex.vars.base import Var
class MatchState(BaseState):
@@ -35,53 +35,53 @@ def test_match_components():
[match_child] = match_dict["children"]
assert match_child["name"] == "match"
- assert str(match_child["cond"]) == "{match_state.value}"
+ assert str(match_child["cond"]) == f"{MatchState.get_name()}.value"
match_cases = match_child["match_cases"]
assert len(match_cases) == 6
- assert match_cases[0][0]._var_name == "1"
- assert match_cases[0][0]._var_type == int
+ assert match_cases[0][0]._js_expr == "1"
+ assert match_cases[0][0]._var_type is int
first_return_value_render = match_cases[0][1].render()
assert first_return_value_render["name"] == "RadixThemesText"
- assert first_return_value_render["children"][0]["contents"] == "{`first value`}"
+ assert first_return_value_render["children"][0]["contents"] == '{"first value"}'
- assert match_cases[1][0]._var_name == "2"
- assert match_cases[1][0]._var_type == int
- assert match_cases[1][1]._var_name == "3"
- assert match_cases[1][1]._var_type == int
+ assert match_cases[1][0]._js_expr == "2"
+ assert match_cases[1][0]._var_type is int
+ assert match_cases[1][1]._js_expr == "3"
+ assert match_cases[1][1]._var_type is int
second_return_value_render = match_cases[1][2].render()
assert second_return_value_render["name"] == "RadixThemesText"
- assert second_return_value_render["children"][0]["contents"] == "{`second value`}"
+ assert second_return_value_render["children"][0]["contents"] == '{"second value"}'
- assert match_cases[2][0]._var_name == "[1, 2]"
- assert match_cases[2][0]._var_type == list
+ assert match_cases[2][0]._js_expr == "[1, 2]"
+ assert match_cases[2][0]._var_type == List[int]
third_return_value_render = match_cases[2][1].render()
assert third_return_value_render["name"] == "RadixThemesText"
- assert third_return_value_render["children"][0]["contents"] == "{`third value`}"
+ assert third_return_value_render["children"][0]["contents"] == '{"third value"}'
- assert match_cases[3][0]._var_name == "random"
- assert match_cases[3][0]._var_type == str
+ assert match_cases[3][0]._js_expr == '"random"'
+ assert match_cases[3][0]._var_type is str
fourth_return_value_render = match_cases[3][1].render()
assert fourth_return_value_render["name"] == "RadixThemesText"
- assert fourth_return_value_render["children"][0]["contents"] == "{`fourth value`}"
+ assert fourth_return_value_render["children"][0]["contents"] == '{"fourth value"}'
- assert match_cases[4][0]._var_name == '{"foo": "bar"}'
- assert match_cases[4][0]._var_type == dict
+ assert match_cases[4][0]._js_expr == '({ ["foo"] : "bar" })'
+ assert match_cases[4][0]._var_type == Dict[str, str]
fifth_return_value_render = match_cases[4][1].render()
assert fifth_return_value_render["name"] == "RadixThemesText"
- assert fifth_return_value_render["children"][0]["contents"] == "{`fifth value`}"
+ assert fifth_return_value_render["children"][0]["contents"] == '{"fifth value"}'
- assert match_cases[5][0]._var_name == "((match_state.num) + (1))"
- assert match_cases[5][0]._var_type == int
+ assert match_cases[5][0]._js_expr == f"({MatchState.get_name()}.num + 1)"
+ assert match_cases[5][0]._var_type is int
fifth_return_value_render = match_cases[5][1].render()
assert fifth_return_value_render["name"] == "RadixThemesText"
- assert fifth_return_value_render["children"][0]["contents"] == "{`sixth value`}"
+ assert fifth_return_value_render["children"][0]["contents"] == '{"sixth value"}'
default = match_child["default"].render()
assert default["name"] == "RadixThemesText"
- assert default["children"][0]["contents"] == "{`default value`}"
+ assert default["children"][0]["contents"] == '{"default value"}'
@pytest.mark.parametrize(
@@ -99,12 +99,12 @@ def test_match_components():
(MatchState.string, f"{MatchState.value} - string"),
"default value",
),
- "(() => { switch (JSON.stringify(match_state.value)) {case JSON.stringify(1): return (`first`); break;case JSON.stringify(2): case JSON.stringify(3): return "
- "(`second value`); break;case JSON.stringify([1, 2]): return (`third-value`); break;case JSON.stringify(`random`): "
- 'return (`fourth_value`); break;case JSON.stringify({"foo": "bar"}): return (`fifth value`); '
- "break;case JSON.stringify(((match_state.num) + (1))): return (`sixth value`); break;case JSON.stringify(`${match_state.value} - string`): "
- "return (match_state.string); break;case JSON.stringify(match_state.string): return (`${match_state.value} - string`); break;default: "
- "return (`default value`); break;};})()",
+ f'(() => {{ switch (JSON.stringify({MatchState.get_name()}.value)) {{case JSON.stringify(1): return ("first"); break;case JSON.stringify(2): case JSON.stringify(3): return '
+ '("second value"); break;case JSON.stringify([1, 2]): return ("third-value"); break;case JSON.stringify("random"): '
+ 'return ("fourth_value"); break;case JSON.stringify(({ ["foo"] : "bar" })): return ("fifth value"); '
+ f'break;case JSON.stringify(({MatchState.get_name()}.num + 1)): return ("sixth value"); break;case JSON.stringify(({MatchState.get_name()}.value+" - string")): '
+ f'return ({MatchState.get_name()}.string); break;case JSON.stringify({MatchState.get_name()}.string): return (({MatchState.get_name()}.value+" - string")); break;default: '
+ 'return ("default value"); break;};})()',
),
(
(
@@ -118,12 +118,12 @@ def test_match_components():
(MatchState.string, f"{MatchState.value} - string"),
MatchState.string,
),
- "(() => { switch (JSON.stringify(match_state.value)) {case JSON.stringify(1): return (`first`); break;case JSON.stringify(2): case JSON.stringify(3): return "
- "(`second value`); break;case JSON.stringify([1, 2]): return (`third-value`); break;case JSON.stringify(`random`): "
- 'return (`fourth_value`); break;case JSON.stringify({"foo": "bar"}): return (`fifth value`); '
- "break;case JSON.stringify(((match_state.num) + (1))): return (`sixth value`); break;case JSON.stringify(`${match_state.value} - string`): "
- "return (match_state.string); break;case JSON.stringify(match_state.string): return (`${match_state.value} - string`); break;default: "
- "return (match_state.string); break;};})()",
+ f'(() => {{ switch (JSON.stringify({MatchState.get_name()}.value)) {{case JSON.stringify(1): return ("first"); break;case JSON.stringify(2): case JSON.stringify(3): return '
+ '("second value"); break;case JSON.stringify([1, 2]): return ("third-value"); break;case JSON.stringify("random"): '
+ 'return ("fourth_value"); break;case JSON.stringify(({ ["foo"] : "bar" })): return ("fifth value"); '
+ f'break;case JSON.stringify(({MatchState.get_name()}.num + 1)): return ("sixth value"); break;case JSON.stringify(({MatchState.get_name()}.value+" - string")): '
+ f'return ({MatchState.get_name()}.string); break;case JSON.stringify({MatchState.get_name()}.string): return (({MatchState.get_name()}.value+" - string")); break;default: '
+ f"return ({MatchState.get_name()}.string); break;}};}})()",
),
],
)
@@ -135,8 +135,8 @@ def test_match_vars(cases, expected):
expected: The expected var full name.
"""
match_comp = Match.create(MatchState.value, *cases)
- assert isinstance(match_comp, BaseVar)
- assert match_comp._var_full_name == expected
+ assert isinstance(match_comp, Var)
+ assert str(match_comp) == expected
def test_match_on_component_without_default():
@@ -247,8 +247,8 @@ def test_match_case_tuple_elements(match_case):
(MatchState.num + 1, "black"),
rx.text("default value"),
),
- "Match cases should have the same return types. Case 3 with return value `red` of type "
- " is not ",
+ 'Match cases should have the same return types. Case 3 with return value `"red"` of type '
+ " is not ",
),
(
(
@@ -260,8 +260,8 @@ def test_match_case_tuple_elements(match_case):
([1, 2], rx.text("third value")),
rx.text("default value"),
),
- "Match cases should have the same return types. Case 3 with return value ` {`first value`} ` "
- "of type is not ",
+ 'Match cases should have the same return types. Case 3 with return value ` {"first value"} ` '
+ "of type is not ",
),
],
)
diff --git a/tests/components/core/test_responsive.py b/tests/units/components/core/test_responsive.py
similarity index 100%
rename from tests/components/core/test_responsive.py
rename to tests/units/components/core/test_responsive.py
diff --git a/tests/components/core/test_upload.py b/tests/units/components/core/test_upload.py
similarity index 79%
rename from tests/components/core/test_upload.py
rename to tests/units/components/core/test_upload.py
index e6b27effc..710baa161 100644
--- a/tests/components/core/test_upload.py
+++ b/tests/units/components/core/test_upload.py
@@ -1,3 +1,6 @@
+from typing import Any
+
+from reflex import event
from reflex.components.core.upload import (
StyledUpload,
Upload,
@@ -8,13 +11,14 @@ from reflex.components.core.upload import (
)
from reflex.event import EventSpec
from reflex.state import State
-from reflex.vars import Var
+from reflex.vars.base import LiteralVar, Var
-class TestUploadState(State):
+class UploadStateTest(State):
"""Test upload state."""
- def drop_handler(self, files):
+ @event
+ def drop_handler(self, files: Any):
"""Handle the drop event.
Args:
@@ -22,7 +26,8 @@ class TestUploadState(State):
"""
pass
- def not_drop_handler(self, not_files):
+ @event
+ def not_drop_handler(self, not_files: Any):
"""Handle the drop event without defining the files argument.
Args:
@@ -42,7 +47,7 @@ def test_get_upload_url():
def test__on_drop_spec():
- assert isinstance(_on_drop_spec(Var.create([])), list)
+ assert isinstance(_on_drop_spec(LiteralVar.create([])), tuple)
def test_upload_create():
@@ -55,7 +60,7 @@ def test_upload_create():
up_comp_2 = Upload.create(
id="foo_id",
- on_drop=TestUploadState.drop_handler([]), # type: ignore
+ on_drop=UploadStateTest.drop_handler([]), # type: ignore
)
assert isinstance(up_comp_2, Upload)
assert up_comp_2.is_used
@@ -65,7 +70,7 @@ def test_upload_create():
up_comp_3 = Upload.create(
id="foo_id",
- on_drop=TestUploadState.drop_handler,
+ on_drop=UploadStateTest.drop_handler,
)
assert isinstance(up_comp_3, Upload)
assert up_comp_3.is_used
@@ -75,7 +80,7 @@ def test_upload_create():
up_comp_4 = Upload.create(
id="foo_id",
- on_drop=TestUploadState.not_drop_handler([]), # type: ignore
+ on_drop=UploadStateTest.not_drop_handler([]), # type: ignore
)
assert isinstance(up_comp_4, Upload)
assert up_comp_4.is_used
@@ -91,7 +96,7 @@ def test_styled_upload_create():
styled_up_comp_2 = StyledUpload.create(
id="foo_id",
- on_drop=TestUploadState.drop_handler([]), # type: ignore
+ on_drop=UploadStateTest.drop_handler([]), # type: ignore
)
assert isinstance(styled_up_comp_2, StyledUpload)
assert styled_up_comp_2.is_used
@@ -101,7 +106,7 @@ def test_styled_upload_create():
styled_up_comp_3 = StyledUpload.create(
id="foo_id",
- on_drop=TestUploadState.drop_handler,
+ on_drop=UploadStateTest.drop_handler,
)
assert isinstance(styled_up_comp_3, StyledUpload)
assert styled_up_comp_3.is_used
@@ -111,7 +116,7 @@ def test_styled_upload_create():
styled_up_comp_4 = StyledUpload.create(
id="foo_id",
- on_drop=TestUploadState.not_drop_handler([]), # type: ignore
+ on_drop=UploadStateTest.not_drop_handler([]), # type: ignore
)
assert isinstance(styled_up_comp_4, StyledUpload)
assert styled_up_comp_4.is_used
diff --git a/tests/components/datadisplay/__init__.py b/tests/units/components/datadisplay/__init__.py
similarity index 100%
rename from tests/components/datadisplay/__init__.py
rename to tests/units/components/datadisplay/__init__.py
diff --git a/tests/components/datadisplay/conftest.py b/tests/units/components/datadisplay/conftest.py
similarity index 99%
rename from tests/components/datadisplay/conftest.py
rename to tests/units/components/datadisplay/conftest.py
index 93796ed23..13c571c8c 100644
--- a/tests/components/datadisplay/conftest.py
+++ b/tests/units/components/datadisplay/conftest.py
@@ -1,4 +1,5 @@
"""Data display component tests fixtures."""
+
from typing import List
import pandas as pd
diff --git a/tests/components/datadisplay/test_code.py b/tests/units/components/datadisplay/test_code.py
similarity index 75%
rename from tests/components/datadisplay/test_code.py
rename to tests/units/components/datadisplay/test_code.py
index 64452e90c..809c68fe5 100644
--- a/tests/components/datadisplay/test_code.py
+++ b/tests/units/components/datadisplay/test_code.py
@@ -1,15 +1,16 @@
import pytest
-from reflex.components.datadisplay.code import CodeBlock
+from reflex.components.datadisplay.code import CodeBlock, Theme
@pytest.mark.parametrize(
- "theme, expected", [("light", "one-light"), ("dark", "one-dark")]
+ "theme, expected",
+ [(Theme.one_light, "oneLight"), (Theme.one_dark, "oneDark")],
)
def test_code_light_dark_theme(theme, expected):
code_block = CodeBlock.create(theme=theme)
- assert code_block.theme._var_name == expected # type: ignore
+ assert code_block.theme._js_expr == expected # type: ignore
def generate_custom_code(language, expected_case):
diff --git a/tests/units/components/datadisplay/test_dataeditor.py b/tests/units/components/datadisplay/test_dataeditor.py
new file mode 100644
index 000000000..63b156e74
--- /dev/null
+++ b/tests/units/components/datadisplay/test_dataeditor.py
@@ -0,0 +1,11 @@
+from reflex.components.datadisplay.dataeditor import DataEditor
+
+
+def test_dataeditor():
+ editor_wrapper = DataEditor.create().render()
+ editor = editor_wrapper["children"][0]
+ assert editor_wrapper["name"] == "div"
+ assert editor_wrapper["props"] == [
+ 'css={({ ["width"] : "100%", ["height"] : "100%" })}'
+ ]
+ assert editor["name"] == "DataEditor"
diff --git a/tests/components/datadisplay/test_datatable.py b/tests/units/components/datadisplay/test_datatable.py
similarity index 90%
rename from tests/components/datadisplay/test_datatable.py
rename to tests/units/components/datadisplay/test_datatable.py
index c755064ce..b3d31ea32 100644
--- a/tests/components/datadisplay/test_datatable.py
+++ b/tests/units/components/datadisplay/test_datatable.py
@@ -16,14 +16,14 @@ from reflex.utils.serializers import serialize, serialize_dataframe
[["foo", "bar"], ["foo1", "bar1"]], columns=["column1", "column2"]
)
},
- "data_table_state.data",
+ "data",
),
- pytest.param({"data": ["foo", "bar"]}, "data_table_state"),
- pytest.param({"data": [["foo", "bar"], ["foo1", "bar1"]]}, "data_table_state"),
+ pytest.param({"data": ["foo", "bar"]}, ""),
+ pytest.param({"data": [["foo", "bar"], ["foo1", "bar1"]]}, ""),
],
indirect=["data_table_state"],
)
-def test_validate_data_table(data_table_state: rx.Var, expected):
+def test_validate_data_table(data_table_state: rx.State, expected):
"""Test the str/render function.
Args:
@@ -40,6 +40,10 @@ def test_validate_data_table(data_table_state: rx.Var, expected):
data_table_dict = data_table_component.render()
+ # prefix expected with state name
+ state_name = data_table_state.get_name()
+ expected = f"{state_name}.{expected}" if expected else state_name
+
assert data_table_dict["props"] == [
f"columns={{{expected}.columns}}",
f"data={{{expected}.data}}",
@@ -114,4 +118,4 @@ def test_serialize_dataframe():
value = serialize(df)
assert value == serialize_dataframe(df)
assert isinstance(value, dict)
- assert list(value.keys()) == ["columns", "data"]
+ assert tuple(value) == ("columns", "data")
diff --git a/tests/units/components/datadisplay/test_shiki_code.py b/tests/units/components/datadisplay/test_shiki_code.py
new file mode 100644
index 000000000..eb473ba06
--- /dev/null
+++ b/tests/units/components/datadisplay/test_shiki_code.py
@@ -0,0 +1,172 @@
+import pytest
+
+from reflex.components.datadisplay.shiki_code_block import (
+ ShikiBaseTransformers,
+ ShikiCodeBlock,
+ ShikiHighLevelCodeBlock,
+ ShikiJsTransformer,
+)
+from reflex.components.el.elements.forms import Button
+from reflex.components.lucide.icon import Icon
+from reflex.components.radix.themes.layout.box import Box
+from reflex.style import Style
+from reflex.vars import Var
+
+
+@pytest.mark.parametrize(
+ "library, fns, expected_output, raises_exception",
+ [
+ ("some_library", ["function_one"], ["function_one"], False),
+ ("some_library", [123], None, True),
+ ("some_library", [], [], False),
+ (
+ "some_library",
+ ["function_one", "function_two"],
+ ["function_one", "function_two"],
+ False,
+ ),
+ ("", ["function_one"], ["function_one"], False),
+ ("some_library", ["function_one", 789], None, True),
+ ("", [], [], False),
+ ],
+)
+def test_create_transformer(library, fns, expected_output, raises_exception):
+ if raises_exception:
+ # Ensure ValueError is raised for invalid cases
+ with pytest.raises(ValueError):
+ ShikiCodeBlock.create_transformer(library, fns)
+ else:
+ transformer = ShikiCodeBlock.create_transformer(library, fns)
+ assert isinstance(transformer, ShikiBaseTransformers)
+ assert transformer.library == library
+
+ # Verify that the functions are correctly wrapped in FunctionStringVar
+ function_names = [str(fn) for fn in transformer.fns]
+ assert function_names == expected_output
+
+
+@pytest.mark.parametrize(
+ "code_block, children, props, expected_first_child, expected_styles",
+ [
+ ("print('Hello')", ["print('Hello')"], {}, "print('Hello')", {}),
+ (
+ "print('Hello')",
+ ["print('Hello')", "More content"],
+ {},
+ "print('Hello')",
+ {},
+ ),
+ (
+ "print('Hello')",
+ ["print('Hello')"],
+ {
+ "transformers": [
+ ShikiBaseTransformers(
+ library="lib", fns=[], style=Style({"color": "red"})
+ )
+ ]
+ },
+ "print('Hello')",
+ {"color": "red"},
+ ),
+ (
+ "print('Hello')",
+ ["print('Hello')"],
+ {
+ "transformers": [
+ ShikiBaseTransformers(
+ library="lib", fns=[], style=Style({"color": "red"})
+ )
+ ],
+ "style": {"background": "blue"},
+ },
+ "print('Hello')",
+ {"color": "red", "background": "blue"},
+ ),
+ ],
+)
+def test_create_shiki_code_block(
+ code_block, children, props, expected_first_child, expected_styles
+):
+ component = ShikiCodeBlock.create(code_block, *children, **props)
+
+ # Test that the created component is a Box
+ assert isinstance(component, Box)
+
+ # Test that the first child is the code
+ code_block_component = component.children[0]
+ assert code_block_component.code._var_value == expected_first_child # type: ignore
+
+ applied_styles = component.style
+ for key, value in expected_styles.items():
+ assert Var.create(applied_styles[key])._var_value == value
+
+
+@pytest.mark.parametrize(
+ "children, props, expected_transformers, expected_button_type",
+ [
+ (["print('Hello')"], {"use_transformers": True}, [ShikiJsTransformer], None),
+ (["print('Hello')"], {"can_copy": True}, None, Button),
+ (
+ ["print('Hello')"],
+ {
+ "can_copy": True,
+ "copy_button": Button.create(Icon.create(tag="a_arrow_down")),
+ },
+ None,
+ Button,
+ ),
+ ],
+)
+def test_create_shiki_high_level_code_block(
+ children, props, expected_transformers, expected_button_type
+):
+ component = ShikiHighLevelCodeBlock.create(*children, **props)
+
+ # Test that the created component is a Box
+ assert isinstance(component, Box)
+
+ # Test that the first child is the code block component
+ code_block_component = component.children[0]
+ assert code_block_component.code._var_value == children[0] # type: ignore
+
+ # Check if the transformer is set correctly if expected
+ if expected_transformers:
+ exp_trans_names = [t.__name__ for t in expected_transformers]
+ for transformer in code_block_component.transformers._var_value: # type: ignore
+ assert type(transformer).__name__ in exp_trans_names
+
+ # Check if the second child is the copy button if can_copy is True
+ if props.get("can_copy", False):
+ if props.get("copy_button"):
+ assert isinstance(component.children[1], expected_button_type)
+ assert component.children[1] == props["copy_button"]
+ else:
+ assert isinstance(component.children[1], expected_button_type)
+ else:
+ assert len(component.children) == 1
+
+
+@pytest.mark.parametrize(
+ "children, props",
+ [
+ (["print('Hello')"], {"theme": "dark"}),
+ (["print('Hello')"], {"language": "javascript"}),
+ ],
+)
+def test_shiki_high_level_code_block_theme_language_mapping(children, props):
+ component = ShikiHighLevelCodeBlock.create(*children, **props)
+
+ # Test that the theme is mapped correctly
+ if "theme" in props:
+ assert component.children[
+ 0
+ ].theme._var_value == ShikiHighLevelCodeBlock._map_themes(props["theme"]) # type: ignore
+
+ # Test that the language is mapped correctly
+ if "language" in props:
+ assert component.children[
+ 0
+ ].language._var_value == ShikiHighLevelCodeBlock._map_languages( # type: ignore
+ props["language"]
+ )
diff --git a/tests/components/el/test_html.py b/tests/units/components/el/test_html.py
similarity index 100%
rename from tests/components/el/test_html.py
rename to tests/units/components/el/test_html.py
diff --git a/tests/units/components/el/test_svg.py b/tests/units/components/el/test_svg.py
new file mode 100644
index 000000000..29aaa96dd
--- /dev/null
+++ b/tests/units/components/el/test_svg.py
@@ -0,0 +1,74 @@
+from reflex.components.el.elements.media import (
+ Circle,
+ Defs,
+ Ellipse,
+ Line,
+ LinearGradient,
+ Path,
+ Polygon,
+ RadialGradient,
+ Rect,
+ Stop,
+ Svg,
+ Text,
+)
+
+
+def test_circle():
+ circle = Circle.create().render()
+ assert circle["name"] == "circle"
+
+
+def test_defs():
+ defs = Defs.create().render()
+ assert defs["name"] == "defs"
+
+
+def test_ellipse():
+ ellipse = Ellipse.create().render()
+ assert ellipse["name"] == "ellipse"
+
+
+def test_line():
+ line = Line.create().render()
+ assert line["name"] == "line"
+
+
+def test_linear_gradient():
+ linear_gradient = LinearGradient.create().render()
+ assert linear_gradient["name"] == "linearGradient"
+
+
+def test_path():
+ path = Path.create().render()
+ assert path["name"] == "path"
+
+
+def test_polygon():
+ polygon = Polygon.create().render()
+ assert polygon["name"] == "polygon"
+
+
+def test_radial_gradient():
+ radial_gradient = RadialGradient.create().render()
+ assert radial_gradient["name"] == "radialGradient"
+
+
+def test_rect():
+ rect = Rect.create().render()
+ assert rect["name"] == "rect"
+
+
+def test_svg():
+ svg = Svg.create().render()
+ assert svg["name"] == "svg"
+
+
+def test_text():
+ text = Text.create().render()
+ assert text["name"] == "text"
+
+
+def test_stop():
+ stop = Stop.create().render()
+ assert stop["name"] == "stop"
diff --git a/tests/components/core/__init__.py b/tests/units/components/forms/__init__.py
similarity index 100%
rename from tests/components/core/__init__.py
rename to tests/units/components/forms/__init__.py
diff --git a/tests/components/forms/test_form.py b/tests/units/components/forms/test_form.py
similarity index 54%
rename from tests/components/forms/test_form.py
rename to tests/units/components/forms/test_form.py
index b9eff2daf..5f3ba2d37 100644
--- a/tests/components/forms/test_form.py
+++ b/tests/units/components/forms/test_form.py
@@ -1,12 +1,12 @@
-from reflex.components.chakra.forms.form import Form
-from reflex.event import EventChain
-from reflex.vars import BaseVar
+from reflex.components.radix.primitives.form import Form
+from reflex.event import EventChain, prevent_default
+from reflex.vars.base import Var
def test_render_on_submit():
"""Test that on_submit event chain is rendered as a separate function."""
- submit_it = BaseVar(
- _var_name="submit_it",
+ submit_it = Var(
+ _js_expr="submit_it",
_var_type=EventChain,
)
f = Form.create(on_submit=submit_it)
@@ -15,7 +15,6 @@ def test_render_on_submit():
def test_render_no_on_submit():
- """A form without on_submit should not render a submit handler."""
+ """A form without on_submit should render a prevent_default handler."""
f = Form.create()
- for prop in f.render()["props"]:
- assert "onSubmit" not in prop
+ assert f.event_triggers["on_submit"] == prevent_default
diff --git a/tests/components/graphing/__init__.py b/tests/units/components/graphing/__init__.py
similarity index 100%
rename from tests/components/graphing/__init__.py
rename to tests/units/components/graphing/__init__.py
diff --git a/tests/components/graphing/test_plotly.py b/tests/units/components/graphing/test_plotly.py
similarity index 96%
rename from tests/components/graphing/test_plotly.py
rename to tests/units/components/graphing/test_plotly.py
index 0e17789b5..69b046bea 100644
--- a/tests/components/graphing/test_plotly.py
+++ b/tests/units/components/graphing/test_plotly.py
@@ -30,7 +30,7 @@ def test_serialize_plotly(plotly_fig: go.Figure):
plotly_fig: The figure to serialize.
"""
value = serialize(plotly_fig)
- assert isinstance(value, list)
+ assert isinstance(value, dict)
assert value == serialize_figure(plotly_fig)
diff --git a/tests/components/graphing/test_recharts.py b/tests/units/components/graphing/test_recharts.py
similarity index 96%
rename from tests/components/graphing/test_recharts.py
rename to tests/units/components/graphing/test_recharts.py
index b87935d1a..c1b986dfd 100644
--- a/tests/components/graphing/test_recharts.py
+++ b/tests/units/components/graphing/test_recharts.py
@@ -1,4 +1,4 @@
-from reflex.components.recharts import (
+from reflex.components.recharts.charts import (
AreaChart,
BarChart,
LineChart,
diff --git a/tests/components/layout/__init__.py b/tests/units/components/layout/__init__.py
similarity index 100%
rename from tests/components/layout/__init__.py
rename to tests/units/components/layout/__init__.py
diff --git a/tests/components/lucide/test_icon.py b/tests/units/components/lucide/test_icon.py
similarity index 59%
rename from tests/components/lucide/test_icon.py
rename to tests/units/components/lucide/test_icon.py
index d61f3a9aa..b0a3475dd 100644
--- a/tests/components/lucide/test_icon.py
+++ b/tests/units/components/lucide/test_icon.py
@@ -1,6 +1,6 @@
import pytest
-from reflex.components.lucide.icon import LUCIDE_ICON_LIST, RENAMED_ICONS_05, Icon
+from reflex.components.lucide.icon import LUCIDE_ICON_LIST, Icon
from reflex.utils import format
@@ -10,16 +10,6 @@ def test_icon(tag):
assert icon.alias == f"Lucide{format.to_title_case(tag)}Icon"
-RENAMED_TAGS = [tag for tag in RENAMED_ICONS_05.items()]
-
-
-@pytest.mark.parametrize("tag, new_tag", RENAMED_TAGS)
-def test_icon_renamed_tags(tag, new_tag):
- Icon.create(tag)
- # TODO: need a PR so we can pass the following test. Currently it fails and uses the old tag as the import.
- # assert icon.alias == f"Lucide{format.to_title_case(new_tag)}Icon"
-
-
def test_icon_missing_tag():
with pytest.raises(AttributeError):
_ = Icon.create()
diff --git a/tests/components/media/__init__.py b/tests/units/components/media/__init__.py
similarity index 100%
rename from tests/components/media/__init__.py
rename to tests/units/components/media/__init__.py
diff --git a/tests/components/media/test_image.py b/tests/units/components/media/test_image.py
similarity index 78%
rename from tests/components/media/test_image.py
rename to tests/units/components/media/test_image.py
index a39895c67..f8618347c 100644
--- a/tests/components/media/test_image.py
+++ b/tests/units/components/media/test_image.py
@@ -1,4 +1,3 @@
-# PIL is only available in python 3.8+
import numpy as np
import PIL
import pytest
@@ -7,6 +6,7 @@ from PIL.Image import Image as Img
import reflex as rx
from reflex.components.next.image import Image # type: ignore
from reflex.utils.serializers import serialize, serialize_image
+from reflex.vars.sequence import StringVar
@pytest.fixture
@@ -36,9 +36,13 @@ def test_set_src_str():
"""Test that setting the src works."""
image = rx.image(src="pic2.jpeg")
# when using next/image, we explicitly create a _var_is_str Var
- # assert str(image.src) == "{`pic2.jpeg`}" # type: ignore
+ assert str(image.src) in ( # type: ignore
+ '"pic2.jpeg"',
+ "'pic2.jpeg'",
+ "`pic2.jpeg`",
+ )
# For plain rx.el.img, an explicit var is not created, so the quoting happens later
- assert str(image.src) == "pic2.jpeg" # type: ignore
+ # assert str(image.src) == "pic2.jpeg" # type: ignore
def test_set_src_img(pil_image: Img):
@@ -48,7 +52,7 @@ def test_set_src_img(pil_image: Img):
pil_image: The image to serialize.
"""
image = Image.create(src=pil_image)
- assert str(image.src._var_name) == serialize_image(pil_image) # type: ignore
+ assert str(image.src._js_expr) == '"' + serialize_image(pil_image) + '"' # type: ignore
def test_render(pil_image: Img):
@@ -58,4 +62,4 @@ def test_render(pil_image: Img):
pil_image: The image to serialize.
"""
image = Image.create(src=pil_image)
- assert image.src._var_is_string # type: ignore
+ assert isinstance(image.src, StringVar) # type: ignore
diff --git a/tests/components/radix/test_icon_button.py b/tests/units/components/radix/test_icon_button.py
similarity index 86%
rename from tests/components/radix/test_icon_button.py
rename to tests/units/components/radix/test_icon_button.py
index 852c0c97c..8047cf7b2 100644
--- a/tests/components/radix/test_icon_button.py
+++ b/tests/units/components/radix/test_icon_button.py
@@ -3,7 +3,7 @@ import pytest
from reflex.components.lucide.icon import Icon
from reflex.components.radix.themes.components.icon_button import IconButton
from reflex.style import Style
-from reflex.vars import Var
+from reflex.vars.base import LiteralVar
def test_icon_button():
@@ -26,5 +26,5 @@ def test_icon_button_size_prop():
ib1 = IconButton.create("activity", size="2")
assert isinstance(ib1, IconButton)
- ib2 = IconButton.create("activity", size=Var.create("2"))
+ ib2 = IconButton.create("activity", size=LiteralVar.create("2"))
assert isinstance(ib2, IconButton)
diff --git a/tests/components/radix/test_layout.py b/tests/units/components/radix/test_layout.py
similarity index 100%
rename from tests/components/radix/test_layout.py
rename to tests/units/components/radix/test_layout.py
diff --git a/tests/units/components/recharts/test_cartesian.py b/tests/units/components/recharts/test_cartesian.py
new file mode 100644
index 000000000..3337427bd
--- /dev/null
+++ b/tests/units/components/recharts/test_cartesian.py
@@ -0,0 +1,50 @@
+from reflex.components.recharts import (
+ Area,
+ Bar,
+ Brush,
+ Line,
+ Scatter,
+ XAxis,
+ YAxis,
+ ZAxis,
+)
+
+
+def test_xaxis():
+ x_axis = XAxis.create("x").render()
+ assert x_axis["name"] == "RechartsXAxis"
+
+
+def test_yaxis():
+ x_axis = YAxis.create("y").render()
+ assert x_axis["name"] == "RechartsYAxis"
+
+
+def test_zaxis():
+ x_axis = ZAxis.create("z").render()
+ assert x_axis["name"] == "RechartsZAxis"
+
+
+def test_brush():
+ brush = Brush.create().render()
+ assert brush["name"] == "RechartsBrush"
+
+
+def test_area():
+ area = Area.create().render()
+ assert area["name"] == "RechartsArea"
+
+
+def test_bar():
+ bar = Bar.create().render()
+ assert bar["name"] == "RechartsBar"
+
+
+def test_line():
+ line = Line.create().render()
+ assert line["name"] == "RechartsLine"
+
+
+def test_scatter():
+ scatter = Scatter.create().render()
+ assert scatter["name"] == "RechartsScatter"
diff --git a/tests/units/components/recharts/test_polar.py b/tests/units/components/recharts/test_polar.py
new file mode 100644
index 000000000..4e4af0f49
--- /dev/null
+++ b/tests/units/components/recharts/test_polar.py
@@ -0,0 +1,38 @@
+from reflex.components.recharts import (
+ Pie,
+ PolarAngleAxis,
+ PolarGrid,
+ PolarRadiusAxis,
+ Radar,
+ RadialBar,
+)
+
+
+def test_pie():
+ pie = Pie.create().render()
+ assert pie["name"] == "RechartsPie"
+
+
+def test_radar():
+ radar = Radar.create().render()
+ assert radar["name"] == "RechartsRadar"
+
+
+def test_radialbar():
+ radialbar = RadialBar.create().render()
+ assert radialbar["name"] == "RechartsRadialBar"
+
+
+def test_polarangleaxis():
+ polarangleaxis = PolarAngleAxis.create().render()
+ assert polarangleaxis["name"] == "RechartsPolarAngleAxis"
+
+
+def test_polargrid():
+ polargrid = PolarGrid.create().render()
+ assert polargrid["name"] == "RechartsPolarGrid"
+
+
+def test_polarradiusaxis():
+ polarradiusaxis = PolarRadiusAxis.create().render()
+ assert polarradiusaxis["name"] == "RechartsPolarRadiusAxis"
diff --git a/tests/components/test_component.py b/tests/units/components/test_component.py
similarity index 73%
rename from tests/components/test_component.py
rename to tests/units/components/test_component.py
index 6245746c9..a614fd715 100644
--- a/tests/components/test_component.py
+++ b/tests/units/components/test_component.py
@@ -8,20 +8,32 @@ from reflex.base import Base
from reflex.compiler.compiler import compile_components
from reflex.components.base.bare import Bare
from reflex.components.base.fragment import Fragment
-from reflex.components.chakra.layout.box import Box
from reflex.components.component import (
Component,
CustomComponent,
StatefulComponent,
custom_component,
)
+from reflex.components.radix.themes.layout.box import Box
from reflex.constants import EventTriggers
-from reflex.event import EventChain, EventHandler, parse_args_spec
+from reflex.event import (
+ EventChain,
+ EventHandler,
+ empty_event,
+ identity_event,
+ input_event,
+ parse_args_spec,
+)
from reflex.state import BaseState
from reflex.style import Style
from reflex.utils import imports
-from reflex.utils.imports import ImportVar
-from reflex.vars import BaseVar, Var, VarData
+from reflex.utils.exceptions import (
+ EventFnArgMismatch,
+ EventHandlerArgMismatch,
+)
+from reflex.utils.imports import ImportDict, ImportVar, ParsedImportDict, parse_imports
+from reflex.vars import VarData
+from reflex.vars.base import LiteralVar, Var
@pytest.fixture
@@ -35,6 +47,18 @@ def test_state():
def do_something_arg(self, arg):
pass
+ def do_something_with_bool(self, arg: bool):
+ pass
+
+ def do_something_with_int(self, arg: int):
+ pass
+
+ def do_something_with_list_int(self, arg: list[int]):
+ pass
+
+ def do_something_with_list_str(self, arg: list[str]):
+ pass
+
return TestState
@@ -56,7 +80,7 @@ def component1() -> Type[Component]:
# A test string/number prop.
text_or_number: Var[Union[int, str]]
- def _get_imports(self) -> imports.ImportDict:
+ def _get_imports(self) -> ParsedImportDict:
return {"react": [ImportVar(tag="Component")]}
def _get_custom_code(self) -> str:
@@ -77,6 +101,8 @@ def component2() -> Type[Component]:
# A test list prop.
arr: Var[List[str]]
+ on_prop_event: EventHandler[lambda e0: [e0]]
+
def get_event_triggers(self) -> Dict[str, Any]:
"""Test controlled triggers.
@@ -85,11 +111,13 @@ def component2() -> Type[Component]:
"""
return {
**super().get_event_triggers(),
- "on_open": lambda e0: [e0],
- "on_close": lambda e0: [e0],
+ "on_open": identity_event(bool),
+ "on_close": identity_event(bool),
+ "on_user_visited_count_changed": identity_event(int),
+ "on_user_list_changed": identity_event(List[str]),
}
- def _get_imports(self) -> imports.ImportDict:
+ def _get_imports(self) -> ParsedImportDict:
return {"react-redux": [ImportVar(tag="connect")]}
def _get_custom_code(self) -> str:
@@ -229,8 +257,8 @@ def test_set_style_attrs(component1):
component1: A test component.
"""
component = component1(color="white", text_align="center")
- assert component.style["color"] == "white"
- assert component.style["textAlign"] == "center"
+ assert str(component.style["color"]) == '"white"'
+ assert str(component.style["textAlign"]) == '"center"'
def test_custom_attrs(component1):
@@ -254,7 +282,10 @@ def test_create_component(component1):
c = component1.create(*children, **attrs)
assert isinstance(c, component1)
assert c.children == children
- assert c.style == {"color": "white", "textAlign": "center"}
+ assert (
+ str(LiteralVar.create(c.style))
+ == '({ ["color"] : "white", ["textAlign"] : "center" })'
+ )
@pytest.mark.parametrize(
@@ -262,121 +293,121 @@ def test_create_component(component1):
[
pytest.param(
"text",
- Var.create("hello"),
+ LiteralVar.create("hello"),
None,
id="text",
),
pytest.param(
"text",
- BaseVar(_var_name="hello", _var_type=Optional[str]),
+ Var(_js_expr="hello", _var_type=Optional[str]),
None,
id="text-optional",
),
pytest.param(
"text",
- BaseVar(_var_name="hello", _var_type=Union[str, None]),
+ Var(_js_expr="hello", _var_type=Union[str, None]),
None,
id="text-union-str-none",
),
pytest.param(
"text",
- BaseVar(_var_name="hello", _var_type=Union[None, str]),
+ Var(_js_expr="hello", _var_type=Union[None, str]),
None,
id="text-union-none-str",
),
pytest.param(
"text",
- Var.create(1),
+ LiteralVar.create(1),
TypeError,
id="text-int",
),
pytest.param(
"number",
- Var.create(1),
+ LiteralVar.create(1),
None,
id="number",
),
pytest.param(
"number",
- BaseVar(_var_name="1", _var_type=Optional[int]),
+ Var(_js_expr="1", _var_type=Optional[int]),
None,
id="number-optional",
),
pytest.param(
"number",
- BaseVar(_var_name="1", _var_type=Union[int, None]),
+ Var(_js_expr="1", _var_type=Union[int, None]),
None,
id="number-union-int-none",
),
pytest.param(
"number",
- BaseVar(_var_name="1", _var_type=Union[None, int]),
+ Var(_js_expr="1", _var_type=Union[None, int]),
None,
id="number-union-none-int",
),
pytest.param(
"number",
- Var.create("1"),
+ LiteralVar.create("1"),
TypeError,
id="number-str",
),
pytest.param(
"text_or_number",
- Var.create("hello"),
+ LiteralVar.create("hello"),
None,
id="text_or_number-str",
),
pytest.param(
"text_or_number",
- Var.create(1),
+ LiteralVar.create(1),
None,
id="text_or_number-int",
),
pytest.param(
"text_or_number",
- BaseVar(_var_name="hello", _var_type=Optional[str]),
+ Var(_js_expr="hello", _var_type=Optional[str]),
None,
id="text_or_number-optional-str",
),
pytest.param(
"text_or_number",
- BaseVar(_var_name="hello", _var_type=Union[str, None]),
+ Var(_js_expr="hello", _var_type=Union[str, None]),
None,
id="text_or_number-union-str-none",
),
pytest.param(
"text_or_number",
- BaseVar(_var_name="hello", _var_type=Union[None, str]),
+ Var(_js_expr="hello", _var_type=Union[None, str]),
None,
id="text_or_number-union-none-str",
),
pytest.param(
"text_or_number",
- BaseVar(_var_name="1", _var_type=Optional[int]),
+ Var(_js_expr="1", _var_type=Optional[int]),
None,
id="text_or_number-optional-int",
),
pytest.param(
"text_or_number",
- BaseVar(_var_name="1", _var_type=Union[int, None]),
+ Var(_js_expr="1", _var_type=Union[int, None]),
None,
id="text_or_number-union-int-none",
),
pytest.param(
"text_or_number",
- BaseVar(_var_name="1", _var_type=Union[None, int]),
+ Var(_js_expr="1", _var_type=Union[None, int]),
None,
id="text_or_number-union-none-int",
),
pytest.param(
"text_or_number",
- Var.create(1.0),
+ LiteralVar.create(1.0),
TypeError,
id="text_or_number-float",
),
pytest.param(
"text_or_number",
- BaseVar(_var_name="hello", _var_type=Optional[Union[str, int]]),
+ Var(_js_expr="hello", _var_type=Optional[Union[str, int]]),
None,
id="text_or_number-optional-union-str-int",
),
@@ -418,8 +449,8 @@ def test_add_style(component1, component2):
}
c1 = component1()._add_style_recursive(style) # type: ignore
c2 = component2()._add_style_recursive(style) # type: ignore
- assert c1.style["color"] == "white"
- assert c2.style["color"] == "black"
+ assert str(c1.style["color"]) == '"white"'
+ assert str(c2.style["color"]) == '"black"'
def test_add_style_create(component1, component2):
@@ -435,8 +466,8 @@ def test_add_style_create(component1, component2):
}
c1 = component1()._add_style_recursive(style) # type: ignore
c2 = component2()._add_style_recursive(style) # type: ignore
- assert c1.style["color"] == "white"
- assert c2.style["color"] == "black"
+ assert str(c1.style["color"]) == '"white"'
+ assert str(c2.style["color"]) == '"black"'
def test_get_imports(component1, component2):
@@ -491,7 +522,7 @@ def test_get_props(component1, component2):
component2: A test component.
"""
assert component1.get_props() == {"text", "number", "text_or_number"}
- assert component2.get_props() == {"arr"}
+ assert component2.get_props() == {"arr", "on_prop_event"}
@pytest.mark.parametrize(
@@ -566,10 +597,17 @@ def test_get_event_triggers(component1, component2):
EventTriggers.ON_MOUNT,
EventTriggers.ON_UNMOUNT,
}
- assert set(component1().get_event_triggers().keys()) == default_triggers
+ assert component1().get_event_triggers().keys() == default_triggers
assert (
component2().get_event_triggers().keys()
- == {"on_open", "on_close"} | default_triggers
+ == {
+ "on_open",
+ "on_close",
+ "on_prop_event",
+ "on_user_visited_count_changed",
+ "on_user_list_changed",
+ }
+ | default_triggers
)
@@ -606,8 +644,8 @@ def test_create_filters_none_props(test_component):
assert "prop4" not in component.get_props()
# Assert that the style prop is present in the component's props
- assert component.style["color"] == "white"
- assert component.style["text-align"] == "center"
+ assert str(component.style["color"]) == '"white"'
+ assert str(component.style["text-align"]) == '"center"'
@pytest.mark.parametrize("children", [((None,),), ("foo", ("bar", (None,)))])
@@ -629,22 +667,19 @@ def test_component_create_unallowed_types(children, test_component):
"name": "Fragment",
"props": [],
"contents": "",
- "args": None,
- "special_props": set(),
+ "special_props": [],
"children": [
{
"name": "RadixThemesText",
- "props": ["as={`p`}"],
+ "props": ['as={"p"}'],
"contents": "",
- "args": None,
- "special_props": set(),
+ "special_props": [],
"children": [
{
"name": "",
"props": [],
- "contents": "{`first_text`}",
- "args": None,
- "special_props": set(),
+ "contents": '{"first_text"}',
+ "special_props": [],
"children": [],
"autofocus": False,
}
@@ -658,123 +693,111 @@ def test_component_create_unallowed_types(children, test_component):
(
(rx.text("first_text"), rx.text("second_text")),
{
- "args": None,
"autofocus": False,
"children": [
{
- "args": None,
"autofocus": False,
"children": [
{
- "args": None,
"autofocus": False,
"children": [],
- "contents": "{`first_text`}",
+ "contents": '{"first_text"}',
"name": "",
"props": [],
- "special_props": set(),
+ "special_props": [],
}
],
"contents": "",
"name": "RadixThemesText",
- "props": ["as={`p`}"],
- "special_props": set(),
+ "props": ['as={"p"}'],
+ "special_props": [],
},
{
- "args": None,
"autofocus": False,
"children": [
{
- "args": None,
"autofocus": False,
"children": [],
- "contents": "{`second_text`}",
+ "contents": '{"second_text"}',
"name": "",
"props": [],
- "special_props": set(),
+ "special_props": [],
}
],
"contents": "",
"name": "RadixThemesText",
- "props": ["as={`p`}"],
- "special_props": set(),
+ "props": ['as={"p"}'],
+ "special_props": [],
},
],
"contents": "",
"name": "Fragment",
"props": [],
- "special_props": set(),
+ "special_props": [],
},
),
(
(rx.text("first_text"), rx.box((rx.text("second_text"),))),
{
- "args": None,
"autofocus": False,
"children": [
{
- "args": None,
"autofocus": False,
"children": [
{
- "args": None,
"autofocus": False,
"children": [],
- "contents": "{`first_text`}",
+ "contents": '{"first_text"}',
"name": "",
"props": [],
- "special_props": set(),
+ "special_props": [],
}
],
"contents": "",
"name": "RadixThemesText",
- "props": ["as={`p`}"],
- "special_props": set(),
+ "props": ['as={"p"}'],
+ "special_props": [],
},
{
- "args": None,
"autofocus": False,
"children": [
{
- "args": None,
"autofocus": False,
"children": [
{
- "args": None,
"autofocus": False,
"children": [
{
- "args": None,
"autofocus": False,
"children": [],
- "contents": "{`second_text`}",
+ "contents": '{"second_text"}',
"name": "",
"props": [],
- "special_props": set(),
+ "special_props": [],
}
],
"contents": "",
"name": "RadixThemesText",
- "props": ["as={`p`}"],
- "special_props": set(),
+ "props": ['as={"p"}'],
+ "special_props": [],
}
],
"contents": "",
"name": "Fragment",
"props": [],
- "special_props": set(),
+ "special_props": [],
}
],
"contents": "",
"name": "RadixThemesBox",
"props": [],
- "special_props": set(),
+ "special_props": [],
},
],
"contents": "",
"name": "Fragment",
"props": [],
- "special_props": set(),
+ "special_props": [],
},
),
],
@@ -824,9 +847,9 @@ def test_component_event_trigger_arbitrary_args():
comp = C1.create(on_foo=C1State.mock_handler)
assert comp.render()["props"][0] == (
- "onFoo={(__e,_alpha,_bravo,_charlie) => addEvents("
- '[Event("c1_state.mock_handler", {_e:__e.target.value,_bravo:_bravo["nested"],_charlie:((_charlie.custom) + (42))})], '
- "(__e,_alpha,_bravo,_charlie), {})}"
+ "onFoo={((__e, _alpha, _bravo, _charlie) => ((addEvents("
+ f'[(Event("{C1State.get_full_name()}.mock_handler", ({{ ["_e"] : __e["target"]["value"], ["_bravo"] : _bravo["nested"], ["_charlie"] : (_charlie["custom"] + 42) }}), ({{ }})))], '
+ "[__e, _alpha, _bravo, _charlie], ({ })))))}"
)
@@ -866,7 +889,7 @@ def test_custom_component_wrapper():
from reflex.components.radix.themes.typography.text import Text
ccomponent = my_component(
- rx.text("child"), width=Var.create(1), color=Var.create("red")
+ rx.text("child"), width=LiteralVar.create(1), color=LiteralVar.create("red")
)
assert isinstance(ccomponent, CustomComponent)
assert len(ccomponent.children) == 1
@@ -883,18 +906,121 @@ def test_invalid_event_handler_args(component2, test_state):
component2: A test component.
test_state: A test state.
"""
- # Uncontrolled event handlers should not take args.
- # This is okay.
- component2.create(on_click=test_state.do_something)
- # This is not okay.
- with pytest.raises(ValueError):
+ # EventHandler args must match
+ with pytest.raises(EventHandlerArgMismatch):
component2.create(on_click=test_state.do_something_arg)
+ with pytest.raises(EventHandlerArgMismatch):
component2.create(on_open=test_state.do_something)
+ with pytest.raises(EventHandlerArgMismatch):
+ component2.create(on_prop_event=test_state.do_something)
+
+ # Multiple EventHandler args: all must match
+ with pytest.raises(EventHandlerArgMismatch):
+ component2.create(
+ on_click=[test_state.do_something_arg, test_state.do_something]
+ )
+ with pytest.raises(EventHandlerArgMismatch):
component2.create(
on_open=[test_state.do_something_arg, test_state.do_something]
)
- # However lambdas are okay.
+ with pytest.raises(EventHandlerArgMismatch):
+ component2.create(
+ on_prop_event=[test_state.do_something_arg, test_state.do_something]
+ )
+
+ # Enable when 0.7.0 happens
+ # # Event Handler types must match
+ # with pytest.raises(EventHandlerArgTypeMismatch):
+ # component2.create(
+ # on_user_visited_count_changed=test_state.do_something_with_bool
+ # )
+ # with pytest.raises(EventHandlerArgTypeMismatch):
+ # component2.create(on_user_list_changed=test_state.do_something_with_int)
+ # with pytest.raises(EventHandlerArgTypeMismatch):
+ # component2.create(on_user_list_changed=test_state.do_something_with_list_int)
+
+ # component2.create(on_open=test_state.do_something_with_int)
+ # component2.create(on_open=test_state.do_something_with_bool)
+ # component2.create(on_user_visited_count_changed=test_state.do_something_with_int)
+ # component2.create(on_user_list_changed=test_state.do_something_with_list_str)
+
+ # lambda cannot return weird values.
+ with pytest.raises(ValueError):
+ component2.create(on_click=lambda: 1)
+ with pytest.raises(ValueError):
+ component2.create(on_click=lambda: [1])
+ with pytest.raises(ValueError):
+ component2.create(
+ on_click=lambda: (test_state.do_something_arg(1), test_state.do_something)
+ )
+
+ # lambda signature must match event trigger.
+ with pytest.raises(EventFnArgMismatch):
+ component2.create(on_click=lambda _: test_state.do_something_arg(1))
+ with pytest.raises(EventFnArgMismatch):
+ component2.create(on_open=lambda: test_state.do_something)
+ with pytest.raises(EventFnArgMismatch):
+ component2.create(on_prop_event=lambda: test_state.do_something)
+
+ # lambda returning EventHandler must match spec
+ with pytest.raises(EventHandlerArgMismatch):
+ component2.create(on_click=lambda: test_state.do_something_arg)
+ with pytest.raises(EventHandlerArgMismatch):
+ component2.create(on_open=lambda _: test_state.do_something)
+ with pytest.raises(EventHandlerArgMismatch):
+ component2.create(on_prop_event=lambda _: test_state.do_something)
+
+ # Mixed EventSpec and EventHandler must match spec.
+ with pytest.raises(EventHandlerArgMismatch):
+ component2.create(
+ on_click=lambda: [
+ test_state.do_something_arg(1),
+ test_state.do_something_arg,
+ ]
+ )
+ with pytest.raises(EventHandlerArgMismatch):
+ component2.create(
+ on_open=lambda _: [test_state.do_something_arg(1), test_state.do_something]
+ )
+ with pytest.raises(EventHandlerArgMismatch):
+ component2.create(
+ on_prop_event=lambda _: [
+ test_state.do_something_arg(1),
+ test_state.do_something,
+ ]
+ )
+
+
+def test_valid_event_handler_args(component2, test_state):
+ """Test that an valid event handler args do not raise exception.
+
+ Args:
+ component2: A test component.
+ test_state: A test state.
+ """
+ # Uncontrolled event handlers should not take args.
+ component2.create(on_click=test_state.do_something)
+ component2.create(on_click=test_state.do_something_arg(1))
+
+ # Controlled event handlers should take args.
+ component2.create(on_open=test_state.do_something_arg)
+ component2.create(on_prop_event=test_state.do_something_arg)
+
+ # Using a partial event spec bypasses arg validation (ignoring the args).
+ component2.create(on_open=test_state.do_something())
+ component2.create(on_prop_event=test_state.do_something())
+
+ # lambda returning EventHandler is okay if the spec matches.
+ component2.create(on_click=lambda: test_state.do_something)
+ component2.create(on_open=lambda _: test_state.do_something_arg)
+ component2.create(on_prop_event=lambda _: test_state.do_something_arg)
+
+ # lambda can always return an EventSpec.
component2.create(on_click=lambda: test_state.do_something_arg(1))
+ component2.create(on_open=lambda _: test_state.do_something_arg(1))
+ component2.create(on_prop_event=lambda _: test_state.do_something_arg(1))
+
+ # Return EventSpec and EventHandler (no arg).
component2.create(
on_click=lambda: [test_state.do_something_arg(1), test_state.do_something]
)
@@ -902,9 +1028,24 @@ def test_invalid_event_handler_args(component2, test_state):
on_click=lambda: [test_state.do_something_arg(1), test_state.do_something()]
)
- # Controlled event handlers should take args.
- # This is okay.
- component2.create(on_open=test_state.do_something_arg)
+ # Return 2 EventSpec.
+ component2.create(
+ on_open=lambda _: [test_state.do_something_arg(1), test_state.do_something()]
+ )
+ component2.create(
+ on_prop_event=lambda _: [
+ test_state.do_something_arg(1),
+ test_state.do_something(),
+ ]
+ )
+
+ # Return EventHandler (1 arg) and EventSpec.
+ component2.create(
+ on_open=lambda _: [test_state.do_something_arg, test_state.do_something()]
+ )
+ component2.create(
+ on_prop_event=lambda _: [test_state.do_something_arg, test_state.do_something()]
+ )
def test_get_hooks_nested(component1, component2, component3):
@@ -1002,10 +1143,10 @@ def test_component_with_only_valid_children(fixture, request):
@pytest.mark.parametrize(
"component,rendered",
[
- (rx.text("hi"), "\n {`hi`}\n "),
+ (rx.text("hi"), '\n\n{"hi"}\n '),
(
- rx.box(rx.chakra.heading("test", size="md")),
- "\n \n {`test`}\n \n ",
+ rx.box(rx.heading("test", size="3")),
+ '\n\n\n\n{"test"}\n \n ',
),
],
)
@@ -1060,44 +1201,43 @@ def test_stateful_banner():
assert isinstance(stateful_component, StatefulComponent)
-TEST_VAR = Var.create_safe("test")._replace(
+TEST_VAR = LiteralVar.create("test")._replace(
merge_var_data=VarData(
hooks={"useTest": None},
- imports={"test": {ImportVar(tag="test")}},
+ imports={"test": [ImportVar(tag="test")]},
state="Test",
- interpolations=[],
)
)
-FORMATTED_TEST_VAR = Var.create(f"foo{TEST_VAR}bar")
-STYLE_VAR = TEST_VAR._replace(_var_name="style", _var_is_local=False)
-EVENT_CHAIN_VAR = TEST_VAR._replace(_var_type=EventChain)
-ARG_VAR = Var.create("arg")
+FORMATTED_TEST_VAR = LiteralVar.create(f"foo{TEST_VAR}bar")
+STYLE_VAR = TEST_VAR._replace(_js_expr="style")
+EVENT_CHAIN_VAR = TEST_VAR.to(EventChain)
+ARG_VAR = Var(_js_expr="arg")
-TEST_VAR_DICT_OF_DICT = Var.create_safe({"a": {"b": "test"}})._replace(
+TEST_VAR_DICT_OF_DICT = LiteralVar.create({"a": {"b": "test"}})._replace(
merge_var_data=TEST_VAR._var_data
)
-FORMATTED_TEST_VAR_DICT_OF_DICT = Var.create_safe({"a": {"b": f"footestbar"}})._replace(
+FORMATTED_TEST_VAR_DICT_OF_DICT = LiteralVar.create(
+ {"a": {"b": f"footestbar"}}
+)._replace(merge_var_data=TEST_VAR._var_data)
+
+TEST_VAR_LIST_OF_LIST = LiteralVar.create([["test"]])._replace(
+ merge_var_data=TEST_VAR._var_data
+)
+FORMATTED_TEST_VAR_LIST_OF_LIST = LiteralVar.create([["footestbar"]])._replace(
merge_var_data=TEST_VAR._var_data
)
-TEST_VAR_LIST_OF_LIST = Var.create_safe([["test"]])._replace(
- merge_var_data=TEST_VAR._var_data
-)
-FORMATTED_TEST_VAR_LIST_OF_LIST = Var.create_safe([["footestbar"]])._replace(
+TEST_VAR_LIST_OF_LIST_OF_LIST = LiteralVar.create([[["test"]]])._replace(
merge_var_data=TEST_VAR._var_data
)
+FORMATTED_TEST_VAR_LIST_OF_LIST_OF_LIST = LiteralVar.create(
+ [[["footestbar"]]]
+)._replace(merge_var_data=TEST_VAR._var_data)
-TEST_VAR_LIST_OF_LIST_OF_LIST = Var.create_safe([[["test"]]])._replace(
+TEST_VAR_LIST_OF_DICT = LiteralVar.create([{"a": "test"}])._replace(
merge_var_data=TEST_VAR._var_data
)
-FORMATTED_TEST_VAR_LIST_OF_LIST_OF_LIST = Var.create_safe([[["footestbar"]]])._replace(
- merge_var_data=TEST_VAR._var_data
-)
-
-TEST_VAR_LIST_OF_DICT = Var.create_safe([{"a": "test"}])._replace(
- merge_var_data=TEST_VAR._var_data
-)
-FORMATTED_TEST_VAR_LIST_OF_DICT = Var.create_safe([{"a": "footestbar"}])._replace(
+FORMATTED_TEST_VAR_LIST_OF_DICT = LiteralVar.create([{"a": "footestbar"}])._replace(
merge_var_data=TEST_VAR._var_data
)
@@ -1116,6 +1256,7 @@ class EventState(rx.State):
v: int = 42
+ @rx.event
def handler(self):
"""A handler that does nothing."""
@@ -1181,12 +1322,22 @@ class EventState(rx.State):
id="fstring-class_name",
),
pytest.param(
- rx.fragment(special_props={TEST_VAR}),
+ rx.fragment(class_name=f"foo{TEST_VAR}bar other-class"),
+ [LiteralVar.create(f"{FORMATTED_TEST_VAR} other-class")],
+ id="fstring-dual-class_name",
+ ),
+ pytest.param(
+ rx.fragment(class_name=[TEST_VAR, "other-class"]),
+ [LiteralVar.create([TEST_VAR, "other-class"]).join(" ")],
+ id="fstring-dual-class_name",
+ ),
+ pytest.param(
+ rx.fragment(special_props=[TEST_VAR]),
[TEST_VAR],
id="direct-special_props",
),
pytest.param(
- rx.fragment(special_props={Var.create(f"foo{TEST_VAR}bar")}),
+ rx.fragment(special_props=[LiteralVar.create(f"foo{TEST_VAR}bar")]),
[FORMATTED_TEST_VAR],
id="fstring-special_props",
),
@@ -1289,12 +1440,15 @@ class EventState(rx.State):
),
)
def test_get_vars(component, exp_vars):
- comp_vars = sorted(component._get_vars(), key=lambda v: v._var_name)
+ comp_vars = sorted(component._get_vars(), key=lambda v: v._js_expr)
assert len(comp_vars) == len(exp_vars)
+ print(comp_vars, exp_vars)
for comp_var, exp_var in zip(
comp_vars,
- sorted(exp_vars, key=lambda v: v._var_name),
+ sorted(exp_vars, key=lambda v: v._js_expr),
):
+ # print(str(comp_var), str(exp_var))
+ # print(comp_var._get_all_var_data(), exp_var._get_all_var_data())
assert comp_var.equals(exp_var)
@@ -1320,10 +1474,26 @@ def test_instantiate_all_components():
"Tfoot",
"Thead",
}
- for component_name in rx._ALL_COMPONENTS: # type: ignore
+ component_nested_list = [
+ *rx.RADIX_MAPPING.values(),
+ *rx.COMPONENTS_BASE_MAPPING.values(),
+ *rx.COMPONENTS_CORE_MAPPING.values(),
+ ]
+ for component_name in [
+ comp_name
+ for submodule_list in component_nested_list
+ for comp_name in submodule_list
+ ]: # type: ignore
if component_name in untested_components:
continue
- component = getattr(rx, component_name)
+ component = getattr(
+ rx,
+ (
+ component_name
+ if not isinstance(component_name, tuple)
+ else component_name[1]
+ ),
+ )
if isinstance(component, type) and issubclass(component, Component):
component.create()
@@ -1390,7 +1560,7 @@ def test_validate_valid_children():
True,
rx.fragment(valid_component2()),
rx.fragment(
- rx.foreach(Var.create([1, 2, 3]), lambda x: valid_component2(x)) # type: ignore
+ rx.foreach(LiteralVar.create([1, 2, 3]), lambda x: valid_component2(x)) # type: ignore
),
)
)
@@ -1450,7 +1620,7 @@ def test_validate_valid_parents():
rx.fragment(valid_component3()),
rx.fragment(
rx.foreach(
- Var.create([1, 2, 3]), # type: ignore
+ LiteralVar.create([1, 2, 3]), # type: ignore
lambda x: valid_component2(valid_component3(x)),
)
),
@@ -1517,7 +1687,9 @@ def test_validate_invalid_children():
True,
rx.fragment(invalid_component()),
rx.fragment(
- rx.foreach(Var.create([1, 2, 3]), lambda x: invalid_component(x)) # type: ignore
+ rx.foreach(
+ LiteralVar.create([1, 2, 3]), lambda x: invalid_component(x)
+ ) # type: ignore
),
)
)
@@ -1580,70 +1752,14 @@ def test_rename_props():
c1 = C1.create(prop1="prop1_1", prop2="prop2_1")
rendered_c1 = c1.render()
- assert "renamed_prop1={`prop1_1`}" in rendered_c1["props"]
- assert "renamed_prop2={`prop2_1`}" in rendered_c1["props"]
+ assert 'renamed_prop1={"prop1_1"}' in rendered_c1["props"]
+ assert 'renamed_prop2={"prop2_1"}' in rendered_c1["props"]
c2 = C2.create(prop1="prop1_2", prop2="prop2_2", prop3="prop3_2")
rendered_c2 = c2.render()
- assert "renamed_prop1={`prop1_2`}" in rendered_c2["props"]
- assert "subclass_prop2={`prop2_2`}" in rendered_c2["props"]
- assert "renamed_prop3={`prop3_2`}" in rendered_c2["props"]
-
-
-def test_deprecated_props(capsys):
- """Assert that deprecated underscore suffix props are translated.
-
- Args:
- capsys: Pytest fixture for capturing stdout and stderr.
- """
-
- class C1(Component):
- tag = "C1"
-
- type: Var[str]
- min: Var[str]
- max: Var[str]
-
- # No warnings are emitted when using the new prop names.
- c1_1 = C1.create(type="type1", min="min1", max="max1")
- out_err = capsys.readouterr()
- assert not out_err.err
- assert not out_err.out
-
- c1_1_render = c1_1.render()
- assert "type={`type1`}" in c1_1_render["props"]
- assert "min={`min1`}" in c1_1_render["props"]
- assert "max={`max1`}" in c1_1_render["props"]
-
- # Deprecation warning is emitted with underscore suffix,
- # but the component still works.
- c1_2 = C1.create(type_="type2", min_="min2", max_="max2")
- out_err = capsys.readouterr()
- assert out_err.out.count("DeprecationWarning:") == 3
- assert not out_err.err
-
- c1_2_render = c1_2.render()
- assert "type={`type2`}" in c1_2_render["props"]
- assert "min={`min2`}" in c1_2_render["props"]
- assert "max={`max2`}" in c1_2_render["props"]
-
- class C2(Component):
- tag = "C2"
-
- type_: Var[str]
- min_: Var[str]
- max_: Var[str]
-
- # No warnings are emitted if the actual prop has an underscore suffix
- c2_1 = C2.create(type_="type1", min_="min1", max_="max1")
- out_err = capsys.readouterr()
- assert not out_err.err
- assert not out_err.out
-
- c2_1_render = c2_1.render()
- assert "type={`type1`}" in c2_1_render["props"]
- assert "min={`min1`}" in c2_1_render["props"]
- assert "max={`max1`}" in c2_1_render["props"]
+ assert 'renamed_prop1={"prop1_2"}' in rendered_c2["props"]
+ assert 'subclass_prop2={"prop2_2"}' in rendered_c2["props"]
+ assert 'renamed_prop3={"prop3_2"}' in rendered_c2["props"]
def test_custom_component_get_imports():
@@ -1695,7 +1811,7 @@ def test_custom_component_declare_event_handlers_in_fields():
return {
**super().get_event_triggers(),
"on_a": lambda e0: [e0],
- "on_b": lambda e0: [e0.target.value],
+ "on_b": input_event,
"on_c": lambda e0: [],
"on_d": lambda: [],
"on_e": lambda: [],
@@ -1704,9 +1820,9 @@ def test_custom_component_declare_event_handlers_in_fields():
class TestComponent(Component):
on_a: EventHandler[lambda e0: [e0]]
- on_b: EventHandler[lambda e0: [e0.target.value]]
- on_c: EventHandler[lambda e0: []]
- on_d: EventHandler[lambda: []]
+ on_b: EventHandler[input_event]
+ on_c: EventHandler[empty_event]
+ on_d: EventHandler[empty_event]
on_e: EventHandler
on_f: EventHandler[lambda a, b, c: [c, b, a]]
@@ -1759,21 +1875,15 @@ def test_invalid_event_trigger():
),
)
def test_component_add_imports(tags):
- def _list_to_import_vars(tags: List[str]) -> List[ImportVar]:
- return [
- ImportVar(tag=tag) if not isinstance(tag, ImportVar) else tag
- for tag in tags
- ]
-
class BaseComponent(Component):
- def _get_imports(self) -> imports.ImportDict:
+ def _get_imports(self) -> ImportDict:
return {}
class Reference(Component):
- def _get_imports(self) -> imports.ImportDict:
+ def _get_imports(self) -> ParsedImportDict:
return imports.merge_imports(
super()._get_imports(),
- {"react": _list_to_import_vars(tags)},
+ parse_imports({"react": tags}),
{"foo": [ImportVar(tag="bar")]},
)
@@ -1792,10 +1902,12 @@ def test_component_add_imports(tags):
baseline = Reference.create()
test = Test.create()
- assert baseline._get_all_imports() == {
- "react": _list_to_import_vars(tags),
- "foo": [ImportVar(tag="bar")],
- }
+ assert baseline._get_all_imports() == parse_imports(
+ {
+ "react": tags,
+ "foo": [ImportVar(tag="bar")],
+ }
+ )
assert test._get_all_imports() == baseline._get_all_imports()
@@ -1953,17 +2065,53 @@ def test_component_add_custom_code():
}
+def test_component_add_hooks_var():
+ class HookComponent(Component):
+ def add_hooks(self):
+ return [
+ "const hook3 = useRef(null)",
+ "const hook1 = 42",
+ Var(
+ _js_expr="useEffect(() => () => {}, [])",
+ _var_data=VarData(
+ hooks={
+ "const hook2 = 43": None,
+ "const hook3 = useRef(null)": None,
+ },
+ imports={"react": [ImportVar(tag="useEffect")]},
+ ),
+ ),
+ Var(
+ _js_expr="const hook3 = useRef(null)",
+ _var_data=VarData(imports={"react": [ImportVar(tag="useRef")]}),
+ ),
+ ]
+
+ assert list(HookComponent()._get_all_hooks()) == [
+ "const hook3 = useRef(null)",
+ "const hook1 = 42",
+ "const hook2 = 43",
+ "useEffect(() => () => {}, [])",
+ ]
+ imports = HookComponent()._get_all_imports()
+ assert len(imports) == 1
+ assert "react" in imports
+ assert len(imports["react"]) == 2
+ assert ImportVar(tag="useRef") in imports["react"]
+ assert ImportVar(tag="useEffect") in imports["react"]
+
+
def test_add_style_embedded_vars(test_state: BaseState):
"""Test that add_style works with embedded vars when returning a plain dict.
Args:
test_state: A test state.
"""
- v0 = Var.create_safe("parent")._replace(
+ v0 = LiteralVar.create("parent")._replace(
merge_var_data=VarData(hooks={"useParent": None}), # type: ignore
)
v1 = rx.color("plum", 10)
- v2 = Var.create_safe("text")._replace(
+ v2 = LiteralVar.create("text")._replace(
merge_var_data=VarData(hooks={"useText": None}), # type: ignore
)
@@ -1989,14 +2137,14 @@ def test_add_style_embedded_vars(test_state: BaseState):
page._add_style_recursive(Style())
assert (
- "const test_state = useContext(StateContexts.test_state)"
+ f"const {test_state.get_name()} = useContext(StateContexts.{test_state.get_name()})"
in page._get_all_hooks_internal()
)
assert "useText" in page._get_all_hooks_internal()
assert "useParent" in page._get_all_hooks_internal()
assert (
str(page).count(
- 'css={{"fakeParent": "parent", "color": "var(--plum-10)", "fake": "text", "margin": `${test_state.num}%`}}'
+ f'css={{({{ ["fakeParent"] : "parent", ["color"] : "var(--plum-10)", ["fake"] : "text", ["margin"] : ({test_state.get_name()}.num+"%") }})}}'
)
== 1
)
@@ -2017,7 +2165,134 @@ def test_add_style_foreach():
assert len(page.children[0].children) == 1
# Expect the style to be added to the child of the foreach
- assert 'css={{"color": "red"}}' in str(page.children[0].children[0])
+ assert 'css={({ ["color"] : "red" })}' in str(page.children[0].children[0])
# Expect only one instance of this CSS dict in the rendered page
- assert str(page).count('css={{"color": "red"}}') == 1
+ assert str(page).count('css={({ ["color"] : "red" })}') == 1
+
+
+class TriggerState(rx.State):
+ """Test state with event handlers."""
+
+ @rx.event
+ def do_something(self):
+ """Sample event handler."""
+ pass
+
+
+@pytest.mark.parametrize(
+ "component, output",
+ [
+ (rx.box(rx.text("random text")), False),
+ (
+ rx.box(rx.text("random text", on_click=rx.console_log("log"))),
+ False,
+ ),
+ (
+ rx.box(
+ rx.text("random text", on_click=TriggerState.do_something),
+ rx.text(
+ "random text",
+ on_click=Var(_js_expr="toggleColorMode").to(EventChain),
+ ),
+ ),
+ True,
+ ),
+ (
+ rx.box(
+ rx.text("random text", on_click=rx.console_log("log")),
+ rx.text(
+ "random text",
+ on_click=Var(_js_expr="toggleColorMode").to(EventChain),
+ ),
+ ),
+ False,
+ ),
+ (
+ rx.box(rx.text("random text", on_click=TriggerState.do_something)),
+ True,
+ ),
+ (
+ rx.box(
+ rx.text(
+ "random text",
+ on_click=[rx.console_log("log"), rx.window_alert("alert")],
+ ),
+ ),
+ False,
+ ),
+ (
+ rx.box(
+ rx.text(
+ "random text",
+ on_click=[rx.console_log("log"), TriggerState.do_something],
+ ),
+ ),
+ True,
+ ),
+ (
+ rx.box(
+ rx.text(
+ "random text",
+ on_blur=lambda: TriggerState.do_something,
+ ),
+ ),
+ True,
+ ),
+ ],
+)
+def test_has_state_event_triggers(component, output):
+ assert component._has_stateful_event_triggers() == output
+
+
+class SpecialComponent(Box):
+ """A special component with custom attributes."""
+
+ data_prop: Var[str]
+ aria_prop: Var[str]
+
+
+@pytest.mark.parametrize(
+ ("component_kwargs", "exp_custom_attrs", "exp_style"),
+ [
+ (
+ {"data_test": "test", "aria_test": "test"},
+ {"data-test": "test", "aria-test": "test"},
+ {},
+ ),
+ (
+ {"data-test": "test", "aria-test": "test"},
+ {"data-test": "test", "aria-test": "test"},
+ {},
+ ),
+ (
+ {"custom_attrs": {"data-existing": "test"}, "data_new": "test"},
+ {"data-existing": "test", "data-new": "test"},
+ {},
+ ),
+ (
+ {"data_test": "test", "data_prop": "prop"},
+ {"data-test": "test"},
+ {},
+ ),
+ (
+ {"aria_test": "test", "aria_prop": "prop"},
+ {"aria-test": "test"},
+ {},
+ ),
+ ],
+)
+def test_special_props(component_kwargs, exp_custom_attrs, exp_style):
+ """Test that data_ and aria_ special props are correctly added to the component.
+
+ Args:
+ component_kwargs: The component kwargs.
+ exp_custom_attrs: The expected custom attributes.
+ exp_style: The expected style.
+ """
+ component = SpecialComponent.create(**component_kwargs)
+ assert component.custom_attrs == exp_custom_attrs
+ assert component.style == exp_style
+ for prop in SpecialComponent.get_props():
+ if prop in component_kwargs:
+ assert getattr(component, prop)._var_value == component_kwargs[prop]
diff --git a/tests/components/test_component_future_annotations.py b/tests/units/components/test_component_future_annotations.py
similarity index 84%
rename from tests/components/test_component_future_annotations.py
rename to tests/units/components/test_component_future_annotations.py
index 37aeb813a..44ec52c16 100644
--- a/tests/components/test_component_future_annotations.py
+++ b/tests/units/components/test_component_future_annotations.py
@@ -3,7 +3,7 @@ from __future__ import annotations
from typing import Any
from reflex.components.component import Component
-from reflex.event import EventHandler
+from reflex.event import EventHandler, empty_event, input_event
# This is a repeat of its namesake in test_component.py.
@@ -25,9 +25,9 @@ def test_custom_component_declare_event_handlers_in_fields():
class TestComponent(Component):
on_a: EventHandler[lambda e0: [e0]]
- on_b: EventHandler[lambda e0: [e0.target.value]]
- on_c: EventHandler[lambda e0: []]
- on_d: EventHandler[lambda: []]
+ on_b: EventHandler[input_event]
+ on_c: EventHandler[empty_event]
+ on_d: EventHandler[empty_event]
custom_component = ReferenceComponent.create()
test_component = TestComponent.create()
diff --git a/tests/components/test_component_state.py b/tests/units/components/test_component_state.py
similarity index 89%
rename from tests/components/test_component_state.py
rename to tests/units/components/test_component_state.py
index 0dc0956e2..574997ba5 100644
--- a/tests/components/test_component_state.py
+++ b/tests/units/components/test_component_state.py
@@ -35,8 +35,8 @@ def test_component_state():
assert cs1.State.increment != cs2.State.increment
assert len(cs1.children) == 1
- assert cs1.children[0].render() == Bare.create("{`a`}").render()
+ assert cs1.children[0].render() == Bare.create("a").render()
assert cs1.id == "a"
assert len(cs2.children) == 1
- assert cs2.children[0].render() == Bare.create("{`b`}").render()
+ assert cs2.children[0].render() == Bare.create("b").render()
assert cs2.id == "b"
diff --git a/tests/units/components/test_props.py b/tests/units/components/test_props.py
new file mode 100644
index 000000000..8ab07f135
--- /dev/null
+++ b/tests/units/components/test_props.py
@@ -0,0 +1,63 @@
+import pytest
+
+from reflex.components.props import NoExtrasAllowedProps
+from reflex.utils.exceptions import InvalidPropValueError
+
+try:
+ from pydantic.v1 import ValidationError
+except ModuleNotFoundError:
+ from pydantic import ValidationError
+
+
+class PropA(NoExtrasAllowedProps):
+ """Base prop class."""
+
+ foo: str
+ bar: str
+
+
+class PropB(NoExtrasAllowedProps):
+ """Prop class with nested props."""
+
+ foobar: str
+ foobaz: PropA
+
+
+@pytest.mark.parametrize(
+ "props_class, kwargs, should_raise",
+ [
+ (PropA, {"foo": "value", "bar": "another_value"}, False),
+ (PropA, {"fooz": "value", "bar": "another_value"}, True),
+ (
+ PropB,
+ {
+ "foobaz": {"foo": "value", "bar": "another_value"},
+ "foobar": "foo_bar_value",
+ },
+ False,
+ ),
+ (
+ PropB,
+ {
+ "fooba": {"foo": "value", "bar": "another_value"},
+ "foobar": "foo_bar_value",
+ },
+ True,
+ ),
+ (
+ PropB,
+ {
+ "foobaz": {"foobar": "value", "bar": "another_value"},
+ "foobar": "foo_bar_value",
+ },
+ True,
+ ),
+ ],
+)
+def test_no_extras_allowed_props(props_class, kwargs, should_raise):
+ if should_raise:
+ with pytest.raises((ValidationError, InvalidPropValueError)):
+ props_class(**kwargs)
+ else:
+ props_instance = props_class(**kwargs)
+ assert isinstance(props_instance, props_class)
diff --git a/tests/components/test_tag.py b/tests/units/components/test_tag.py
similarity index 87%
rename from tests/components/test_tag.py
rename to tests/units/components/test_tag.py
index 2fb2f4563..a69e40b8b 100644
--- a/tests/components/test_tag.py
+++ b/tests/units/components/test_tag.py
@@ -3,7 +3,7 @@ from typing import Dict, List
import pytest
from reflex.components.tags import CondTag, Tag, tagless
-from reflex.vars import BaseVar, Var
+from reflex.vars.base import LiteralVar, Var
@pytest.mark.parametrize(
@@ -12,8 +12,8 @@ from reflex.vars import BaseVar, Var
({}, []),
({"key-hypen": 1}, ["key-hypen={1}"]),
({"key": 1}, ["key={1}"]),
- ({"key": "value"}, ["key={`value`}"]),
- ({"key": True, "key2": "value2"}, ["key={true}", "key2={`value2`}"]),
+ ({"key": "value"}, ['key={"value"}']),
+ ({"key": True, "key2": "value2"}, ["key={true}", 'key2={"value2"}']),
],
)
def test_format_props(props: Dict[str, Var], test_props: List):
@@ -53,8 +53,8 @@ def test_is_valid_prop(prop: Var, valid: bool):
def test_add_props():
"""Test that the props are added."""
tag = Tag().add_props(key="value", key2=42, invalid=None, invalid2={})
- assert tag.props["key"].equals(Var.create("value"))
- assert tag.props["key2"].equals(Var.create(42))
+ assert tag.props["key"].equals(LiteralVar.create("value"))
+ assert tag.props["key2"].equals(LiteralVar.create(42))
assert "invalid" not in tag.props
assert "invalid2" not in tag.props
@@ -102,7 +102,7 @@ def test_format_tag(tag: Tag, expected: Dict):
assert tag_dict["name"] == expected["name"]
assert tag_dict["contents"] == expected["contents"]
for prop, prop_value in tag_dict["props"].items():
- assert prop_value.equals(Var.create_safe(expected["props"][prop]))
+ assert prop_value.equals(LiteralVar.create(expected["props"][prop]))
def test_format_cond_tag():
@@ -110,7 +110,7 @@ def test_format_cond_tag():
tag = CondTag(
true_value=dict(Tag(name="h1", contents="True content")),
false_value=dict(Tag(name="h2", contents="False content")),
- cond=BaseVar(_var_name="logged_in", _var_type=bool),
+ cond=Var(_js_expr="logged_in", _var_type=bool),
)
tag_dict = dict(tag)
cond, true_value, false_value = (
@@ -118,8 +118,8 @@ def test_format_cond_tag():
tag_dict["true_value"],
tag_dict["false_value"],
)
- assert cond._var_name == "logged_in"
- assert cond._var_type == bool
+ assert cond._js_expr == "logged_in"
+ assert cond._var_type is bool
assert true_value["name"] == "h1"
assert true_value["contents"] == "True content"
diff --git a/tests/components/forms/__init__.py b/tests/units/components/typography/__init__.py
similarity index 100%
rename from tests/components/forms/__init__.py
rename to tests/units/components/typography/__init__.py
diff --git a/tests/components/typography/test_markdown.py b/tests/units/components/typography/test_markdown.py
similarity index 91%
rename from tests/components/typography/test_markdown.py
rename to tests/units/components/typography/test_markdown.py
index 8033ec606..5e9abbb1f 100644
--- a/tests/components/typography/test_markdown.py
+++ b/tests/units/components/typography/test_markdown.py
@@ -36,9 +36,7 @@ def test_get_component(tag, expected):
def test_set_component_map():
"""Test setting the component map."""
component_map = {
- "h1": lambda value: rx.box(
- rx.chakra.heading(value, as_="h1", size="2xl"), padding="1em"
- ),
+ "h1": lambda value: rx.box(rx.heading(value, as_="h1"), padding="1em"),
"p": lambda value: rx.box(rx.text(value), padding="1em"),
}
md = Markdown.create("# Hello", component_map=component_map)
diff --git a/tests/conftest.py b/tests/units/conftest.py
similarity index 91%
rename from tests/conftest.py
rename to tests/units/conftest.py
index be9290edb..2f619a941 100644
--- a/tests/conftest.py
+++ b/tests/units/conftest.py
@@ -1,16 +1,19 @@
"""Test fixtures."""
+
+import asyncio
import contextlib
import os
import platform
import uuid
from pathlib import Path
-from typing import Dict, Generator
+from typing import Dict, Generator, Type
from unittest import mock
import pytest
from reflex.app import App
from reflex.event import EventSpec
+from reflex.model import ModelRegistry
from reflex.utils import prerequisites
from .states import (
@@ -22,6 +25,11 @@ from .states import (
)
+def pytest_configure(config):
+ if config.getoption("asyncio_mode") == "auto":
+ asyncio.set_event_loop_policy(asyncio.DefaultEventLoopPolicy())
+
+
@pytest.fixture
def app() -> App:
"""A base app.
@@ -229,7 +237,7 @@ def tmp_working_dir(tmp_path):
@pytest.fixture
-def mutable_state():
+def mutable_state() -> MutableTestState:
"""Create a Test state containing mutable types.
Returns:
@@ -246,3 +254,14 @@ def token() -> str:
A fresh/unique token string.
"""
return str(uuid.uuid4())
+
+
+@pytest.fixture
+def model_registry() -> Generator[Type[ModelRegistry], None, None]:
+ """Create a model registry.
+
+ Yields:
+ A fresh model registry.
+ """
+ yield ModelRegistry
+ ModelRegistry._metadata = None
diff --git a/tests/units/experimental/custom_script.js b/tests/units/experimental/custom_script.js
new file mode 100644
index 000000000..81bae3136
--- /dev/null
+++ b/tests/units/experimental/custom_script.js
@@ -0,0 +1 @@
+const test = "inside custom_script.js";
\ No newline at end of file
diff --git a/tests/units/experimental/test_assets.py b/tests/units/experimental/test_assets.py
new file mode 100644
index 000000000..8037bcc75
--- /dev/null
+++ b/tests/units/experimental/test_assets.py
@@ -0,0 +1,36 @@
+import shutil
+from pathlib import Path
+
+import pytest
+
+import reflex as rx
+
+
+def test_asset():
+ # Test the asset function.
+
+ # The asset function copies a file to the app's external assets directory.
+ asset = rx._x.asset("custom_script.js", "subfolder")
+ assert asset == "/external/test_assets/subfolder/custom_script.js"
+ result_file = Path(
+ Path.cwd(), "assets/external/test_assets/subfolder/custom_script.js"
+ )
+ assert result_file.exists()
+
+ # Running a second time should not raise an error.
+ asset = rx._x.asset("custom_script.js", "subfolder")
+
+ # Test the asset function without a subfolder.
+ asset = rx._x.asset("custom_script.js")
+ assert asset == "/external/test_assets/custom_script.js"
+ result_file = Path(Path.cwd(), "assets/external/test_assets/custom_script.js")
+ assert result_file.exists()
+
+ # clean up
+ shutil.rmtree(Path.cwd() / "assets/external")
+
+ with pytest.raises(FileNotFoundError):
+ asset = rx._x.asset("non_existent_file.js")
+
+ # Nothing is done to assets when file does not exist.
+ assert not Path(Path.cwd() / "assets/external").exists()
diff --git a/tests/components/typography/__init__.py b/tests/units/middleware/__init__.py
similarity index 100%
rename from tests/components/typography/__init__.py
rename to tests/units/middleware/__init__.py
diff --git a/tests/middleware/conftest.py b/tests/units/middleware/conftest.py
similarity index 82%
rename from tests/middleware/conftest.py
rename to tests/units/middleware/conftest.py
index 5a1897110..d786db652 100644
--- a/tests/middleware/conftest.py
+++ b/tests/units/middleware/conftest.py
@@ -1,6 +1,7 @@
import pytest
from reflex.event import Event
+from reflex.state import State
def create_event(name):
@@ -21,4 +22,4 @@ def create_event(name):
@pytest.fixture
def event1():
- return create_event("state.hydrate")
+ return create_event(f"{State.get_name()}.hydrate")
diff --git a/tests/middleware/test_hydrate_middleware.py b/tests/units/middleware/test_hydrate_middleware.py
similarity index 100%
rename from tests/middleware/test_hydrate_middleware.py
rename to tests/units/middleware/test_hydrate_middleware.py
diff --git a/tests/states/__init__.py b/tests/units/states/__init__.py
similarity index 99%
rename from tests/states/__init__.py
rename to tests/units/states/__init__.py
index 11e891ab4..6aae7683a 100644
--- a/tests/states/__init__.py
+++ b/tests/units/states/__init__.py
@@ -1,4 +1,5 @@
"""Common rx.BaseState subclasses for use in tests."""
+
import reflex as rx
from reflex.state import BaseState
diff --git a/tests/states/mutation.py b/tests/units/states/mutation.py
similarity index 77%
rename from tests/states/mutation.py
rename to tests/units/states/mutation.py
index 5825b6d12..b05f558a1 100644
--- a/tests/states/mutation.py
+++ b/tests/units/states/mutation.py
@@ -2,8 +2,12 @@
from typing import Dict, List, Set, Union
+from sqlalchemy import ARRAY, JSON, String
+from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
+
import reflex as rx
from reflex.state import BaseState
+from reflex.utils.serializers import serializer
class DictMutationTestState(BaseState):
@@ -145,15 +149,47 @@ class CustomVar(rx.Base):
custom: OtherBase = OtherBase()
+class MutableSQLABase(DeclarativeBase):
+ """SQLAlchemy base model for mutable vars."""
+
+ pass
+
+
+class MutableSQLAModel(MutableSQLABase):
+ """SQLAlchemy model for mutable vars."""
+
+ __tablename__: str = "mutable_test_state"
+
+ id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
+ strlist: Mapped[List[str]] = mapped_column(ARRAY(String))
+ hashmap: Mapped[Dict[str, str]] = mapped_column(JSON)
+ test_set: Mapped[Set[str]] = mapped_column(ARRAY(String))
+
+
+@serializer
+def serialize_mutable_sqla_model(
+ model: MutableSQLAModel,
+) -> Dict[str, Union[List[str], Dict[str, str]]]:
+ """Serialize the MutableSQLAModel.
+
+ Args:
+ model: The MutableSQLAModel instance to serialize.
+
+ Returns:
+ The serialized model.
+ """
+ return {"strlist": model.strlist, "hashmap": model.hashmap}
+
+
class MutableTestState(BaseState):
"""A test state."""
- array: List[Union[str, List, Dict[str, str]]] = [
+ array: List[Union[str, int, List, Dict[str, str]]] = [
"value",
[1, 2, 3],
{"key": "value"},
]
- hashmap: Dict[str, Union[List, str, Dict[str, str]]] = {
+ hashmap: Dict[str, Union[List, str, Dict[str, Union[str, Dict]]]] = {
"key": ["list", "of", "values"],
"another_key": "another_value",
"third_key": {"key": "value"},
@@ -161,6 +197,11 @@ class MutableTestState(BaseState):
test_set: Set[Union[str, int]] = {1, 2, 3, 4, "five"}
custom: CustomVar = CustomVar()
_be_custom: CustomVar = CustomVar()
+ sqla_model: MutableSQLAModel = MutableSQLAModel(
+ strlist=["a", "b", "c"],
+ hashmap={"key": "value"},
+ test_set={"one", "two", "three"},
+ )
def reassign_mutables(self):
"""Assign mutable fields to different values."""
@@ -171,3 +212,8 @@ class MutableTestState(BaseState):
"mod_third_key": {"key": "value"},
}
self.test_set = {1, 2, 3, 4, "five"}
+ self.sqla_model = MutableSQLAModel(
+ strlist=["d", "e", "f"],
+ hashmap={"key": "value"},
+ test_set={"one", "two", "three"},
+ )
diff --git a/tests/states/upload.py b/tests/units/states/upload.py
similarity index 97%
rename from tests/states/upload.py
rename to tests/units/states/upload.py
index 8abe11c24..338025bcd 100644
--- a/tests/states/upload.py
+++ b/tests/units/states/upload.py
@@ -1,4 +1,5 @@
"""Test states for upload-related tests."""
+
from pathlib import Path
from typing import ClassVar, List
@@ -70,7 +71,7 @@ class FileUploadState(State):
assert file.filename is not None
self.img_list.append(file.filename)
- @rx.background
+ @rx.event(background=True)
async def bg_upload(self, files: List[rx.UploadFile]):
"""Background task cannot be upload handler.
@@ -118,7 +119,7 @@ class ChildFileUploadState(FileStateBase1):
assert file.filename is not None
self.img_list.append(file.filename)
- @rx.background
+ @rx.event(background=True)
async def bg_upload(self, files: List[rx.UploadFile]):
"""Background task cannot be upload handler.
@@ -166,7 +167,7 @@ class GrandChildFileUploadState(FileStateBase2):
assert file.filename is not None
self.img_list.append(file.filename)
- @rx.background
+ @rx.event(background=True)
async def bg_upload(self, files: List[rx.UploadFile]):
"""Background task cannot be upload handler.
diff --git a/tests/test_app.py b/tests/units/test_app.py
similarity index 74%
rename from tests/test_app.py
rename to tests/units/test_app.py
index 0e204c7d5..1e34a67c3 100644
--- a/tests/test_app.py
+++ b/tests/units/test_app.py
@@ -1,11 +1,13 @@
from __future__ import annotations
+import functools
import io
import json
import os.path
import re
import unittest.mock
import uuid
+from contextlib import nullcontext as does_not_raise
from pathlib import Path
from typing import Generator, List, Tuple, Type
from unittest.mock import AsyncMock
@@ -27,7 +29,9 @@ from reflex.app import (
process,
upload,
)
-from reflex.components import Component, Cond, Fragment
+from reflex.components import Component
+from reflex.components.base.fragment import Fragment
+from reflex.components.core.cond import Cond
from reflex.components.radix.themes.typography.text import Text
from reflex.event import Event
from reflex.middleware import HydrateMiddleware
@@ -37,6 +41,7 @@ from reflex.state import (
OnLoadInternalState,
RouterData,
State,
+ StateManagerDisk,
StateManagerMemory,
StateManagerRedis,
StateUpdate,
@@ -44,7 +49,7 @@ from reflex.state import (
)
from reflex.style import Style
from reflex.utils import exceptions, format
-from reflex.vars import ComputedVar
+from reflex.vars.base import computed_var
from .conftest import chdir
from .states import (
@@ -63,7 +68,7 @@ class EmptyState(BaseState):
@pytest.fixture
-def index_page():
+def index_page() -> ComponentCallable:
"""An index page.
Returns:
@@ -77,7 +82,7 @@ def index_page():
@pytest.fixture
-def about_page():
+def about_page() -> ComponentCallable:
"""An about page.
Returns:
@@ -232,10 +237,13 @@ def test_add_page_default_route(app: App, index_page, about_page):
about_page: The about page.
"""
assert app.pages == {}
+ assert app.unevaluated_pages == {}
app.add_page(index_page)
- assert set(app.pages.keys()) == {"index"}
+ app._compile_page("index")
+ assert app.pages.keys() == {"index"}
app.add_page(about_page)
- assert set(app.pages.keys()) == {"index", "about"}
+ app._compile_page("about")
+ assert app.pages.keys() == {"index", "about"}
def test_add_page_set_route(app: App, index_page, windows_platform: bool):
@@ -247,9 +255,10 @@ def test_add_page_set_route(app: App, index_page, windows_platform: bool):
windows_platform: Whether the system is windows.
"""
route = "test" if windows_platform else "/test"
- assert app.pages == {}
+ assert app.unevaluated_pages == {}
app.add_page(index_page, route=route)
- assert set(app.pages.keys()) == {"test"}
+ app._compile_page("test")
+ assert app.pages.keys() == {"test"}
def test_add_page_set_route_dynamic(index_page, windows_platform: bool):
@@ -262,11 +271,10 @@ def test_add_page_set_route_dynamic(index_page, windows_platform: bool):
app = App(state=EmptyState)
assert app.state is not None
route = "/test/[dynamic]"
- if windows_platform:
- route.lstrip("/").replace("/", "\\")
- assert app.pages == {}
+ assert app.unevaluated_pages == {}
app.add_page(index_page, route=route)
- assert set(app.pages.keys()) == {"test/[dynamic]"}
+ app._compile_page("test/[dynamic]")
+ assert app.pages.keys() == {"test/[dynamic]"}
assert "dynamic" in app.state.computed_vars
assert app.state.computed_vars["dynamic"]._deps(objclass=EmptyState) == {
constants.ROUTER
@@ -283,9 +291,9 @@ def test_add_page_set_route_nested(app: App, index_page, windows_platform: bool)
windows_platform: Whether the system is windows.
"""
route = "test\\nested" if windows_platform else "/test/nested"
- assert app.pages == {}
+ assert app.unevaluated_pages == {}
app.add_page(index_page, route=route)
- assert set(app.pages.keys()) == {route.strip(os.path.sep)}
+ assert app.unevaluated_pages.keys() == {route.strip(os.path.sep)}
def test_add_page_invalid_api_route(app: App, index_page):
@@ -481,20 +489,12 @@ async def test_dynamic_var_event(test_state: Type[ATestState], token: str):
pytest.param(
[
(
- "list_mutation_test_state.make_friend",
- {
- "list_mutation_test_state": {
- "plain_friends": ["Tommy", "another-fd"]
- }
- },
+ "make_friend",
+ {"plain_friends": ["Tommy", "another-fd"]},
),
(
- "list_mutation_test_state.change_first_friend",
- {
- "list_mutation_test_state": {
- "plain_friends": ["Jenny", "another-fd"]
- }
- },
+ "change_first_friend",
+ {"plain_friends": ["Jenny", "another-fd"]},
),
],
id="append then __setitem__",
@@ -502,12 +502,12 @@ async def test_dynamic_var_event(test_state: Type[ATestState], token: str):
pytest.param(
[
(
- "list_mutation_test_state.unfriend_first_friend",
- {"list_mutation_test_state": {"plain_friends": []}},
+ "unfriend_first_friend",
+ {"plain_friends": []},
),
(
- "list_mutation_test_state.make_friend",
- {"list_mutation_test_state": {"plain_friends": ["another-fd"]}},
+ "make_friend",
+ {"plain_friends": ["another-fd"]},
),
],
id="delitem then append",
@@ -515,24 +515,20 @@ async def test_dynamic_var_event(test_state: Type[ATestState], token: str):
pytest.param(
[
(
- "list_mutation_test_state.make_friends_with_colleagues",
- {
- "list_mutation_test_state": {
- "plain_friends": ["Tommy", "Peter", "Jimmy"]
- }
- },
+ "make_friends_with_colleagues",
+ {"plain_friends": ["Tommy", "Peter", "Jimmy"]},
),
(
- "list_mutation_test_state.remove_tommy",
- {"list_mutation_test_state": {"plain_friends": ["Peter", "Jimmy"]}},
+ "remove_tommy",
+ {"plain_friends": ["Peter", "Jimmy"]},
),
(
- "list_mutation_test_state.remove_last_friend",
- {"list_mutation_test_state": {"plain_friends": ["Peter"]}},
+ "remove_last_friend",
+ {"plain_friends": ["Peter"]},
),
(
- "list_mutation_test_state.unfriend_all_friends",
- {"list_mutation_test_state": {"plain_friends": []}},
+ "unfriend_all_friends",
+ {"plain_friends": []},
),
],
id="extend, remove, pop, clear",
@@ -540,28 +536,16 @@ async def test_dynamic_var_event(test_state: Type[ATestState], token: str):
pytest.param(
[
(
- "list_mutation_test_state.add_jimmy_to_second_group",
- {
- "list_mutation_test_state": {
- "friends_in_nested_list": [["Tommy"], ["Jenny", "Jimmy"]]
- }
- },
+ "add_jimmy_to_second_group",
+ {"friends_in_nested_list": [["Tommy"], ["Jenny", "Jimmy"]]},
),
(
- "list_mutation_test_state.remove_first_person_from_first_group",
- {
- "list_mutation_test_state": {
- "friends_in_nested_list": [[], ["Jenny", "Jimmy"]]
- }
- },
+ "remove_first_person_from_first_group",
+ {"friends_in_nested_list": [[], ["Jenny", "Jimmy"]]},
),
(
- "list_mutation_test_state.remove_first_group",
- {
- "list_mutation_test_state": {
- "friends_in_nested_list": [["Jenny", "Jimmy"]]
- }
- },
+ "remove_first_group",
+ {"friends_in_nested_list": [["Jenny", "Jimmy"]]},
),
],
id="nested list",
@@ -569,24 +553,16 @@ async def test_dynamic_var_event(test_state: Type[ATestState], token: str):
pytest.param(
[
(
- "list_mutation_test_state.add_jimmy_to_tommy_friends",
- {
- "list_mutation_test_state": {
- "friends_in_dict": {"Tommy": ["Jenny", "Jimmy"]}
- }
- },
+ "add_jimmy_to_tommy_friends",
+ {"friends_in_dict": {"Tommy": ["Jenny", "Jimmy"]}},
),
(
- "list_mutation_test_state.remove_jenny_from_tommy",
- {
- "list_mutation_test_state": {
- "friends_in_dict": {"Tommy": ["Jimmy"]}
- }
- },
+ "remove_jenny_from_tommy",
+ {"friends_in_dict": {"Tommy": ["Jimmy"]}},
),
(
- "list_mutation_test_state.tommy_has_no_fds",
- {"list_mutation_test_state": {"friends_in_dict": {"Tommy": []}}},
+ "tommy_has_no_fds",
+ {"friends_in_dict": {"Tommy": []}},
),
],
id="list in dict",
@@ -610,12 +586,14 @@ async def test_list_mutation_detection__plain_list(
result = await list_mutation_state._process(
Event(
token=token,
- name=event_name,
+ name=f"{list_mutation_state.get_name()}.{event_name}",
router_data={"pathname": "/", "query": {}},
payload={},
)
).__anext__()
+ # prefix keys in expected_delta with the state name
+ expected_delta = {list_mutation_state.get_name(): expected_delta}
assert result.delta == expected_delta
@@ -626,24 +604,16 @@ async def test_list_mutation_detection__plain_list(
pytest.param(
[
(
- "dict_mutation_test_state.add_age",
- {
- "dict_mutation_test_state": {
- "details": {"name": "Tommy", "age": 20}
- }
- },
+ "add_age",
+ {"details": {"name": "Tommy", "age": 20}},
),
(
- "dict_mutation_test_state.change_name",
- {
- "dict_mutation_test_state": {
- "details": {"name": "Jenny", "age": 20}
- }
- },
+ "change_name",
+ {"details": {"name": "Jenny", "age": 20}},
),
(
- "dict_mutation_test_state.remove_last_detail",
- {"dict_mutation_test_state": {"details": {"name": "Jenny"}}},
+ "remove_last_detail",
+ {"details": {"name": "Jenny"}},
),
],
id="update then __setitem__",
@@ -651,12 +621,12 @@ async def test_list_mutation_detection__plain_list(
pytest.param(
[
(
- "dict_mutation_test_state.clear_details",
- {"dict_mutation_test_state": {"details": {}}},
+ "clear_details",
+ {"details": {}},
),
(
- "dict_mutation_test_state.add_age",
- {"dict_mutation_test_state": {"details": {"age": 20}}},
+ "add_age",
+ {"details": {"age": 20}},
),
],
id="delitem then update",
@@ -664,20 +634,16 @@ async def test_list_mutation_detection__plain_list(
pytest.param(
[
(
- "dict_mutation_test_state.add_age",
- {
- "dict_mutation_test_state": {
- "details": {"name": "Tommy", "age": 20}
- }
- },
+ "add_age",
+ {"details": {"name": "Tommy", "age": 20}},
),
(
- "dict_mutation_test_state.remove_name",
- {"dict_mutation_test_state": {"details": {"age": 20}}},
+ "remove_name",
+ {"details": {"age": 20}},
),
(
- "dict_mutation_test_state.pop_out_age",
- {"dict_mutation_test_state": {"details": {}}},
+ "pop_out_age",
+ {"details": {}},
),
],
id="add, remove, pop",
@@ -685,22 +651,16 @@ async def test_list_mutation_detection__plain_list(
pytest.param(
[
(
- "dict_mutation_test_state.remove_home_address",
- {
- "dict_mutation_test_state": {
- "address": [{}, {"work": "work address"}]
- }
- },
+ "remove_home_address",
+ {"address": [{}, {"work": "work address"}]},
),
(
- "dict_mutation_test_state.add_street_to_home_address",
+ "add_street_to_home_address",
{
- "dict_mutation_test_state": {
- "address": [
- {"street": "street address"},
- {"work": "work address"},
- ]
- }
+ "address": [
+ {"street": "street address"},
+ {"work": "work address"},
+ ]
},
),
],
@@ -709,34 +669,26 @@ async def test_list_mutation_detection__plain_list(
pytest.param(
[
(
- "dict_mutation_test_state.change_friend_name",
+ "change_friend_name",
{
- "dict_mutation_test_state": {
- "friend_in_nested_dict": {
- "name": "Nikhil",
- "friend": {"name": "Tommy"},
- }
+ "friend_in_nested_dict": {
+ "name": "Nikhil",
+ "friend": {"name": "Tommy"},
}
},
),
(
- "dict_mutation_test_state.add_friend_age",
+ "add_friend_age",
{
- "dict_mutation_test_state": {
- "friend_in_nested_dict": {
- "name": "Nikhil",
- "friend": {"name": "Tommy", "age": 30},
- }
+ "friend_in_nested_dict": {
+ "name": "Nikhil",
+ "friend": {"name": "Tommy", "age": 30},
}
},
),
(
- "dict_mutation_test_state.remove_friend",
- {
- "dict_mutation_test_state": {
- "friend_in_nested_dict": {"name": "Nikhil"}
- }
- },
+ "remove_friend",
+ {"friend_in_nested_dict": {"name": "Nikhil"}},
),
],
id="nested dict",
@@ -760,12 +712,15 @@ async def test_dict_mutation_detection__plain_list(
result = await dict_mutation_state._process(
Event(
token=token,
- name=event_name,
+ name=f"{dict_mutation_state.get_name()}.{event_name}",
router_data={"pathname": "/", "query": {}},
payload={},
)
).__anext__()
+ # prefix keys in expected_delta with the state name
+ expected_delta = {dict_mutation_state.get_name(): expected_delta}
+
assert result.delta == expected_delta
@@ -775,12 +730,16 @@ async def test_dict_mutation_detection__plain_list(
[
(
FileUploadState,
- {"state.file_upload_state": {"img_list": ["image1.jpg", "image2.jpg"]}},
+ {
+ FileUploadState.get_full_name(): {
+ "img_list": ["image1.jpg", "image2.jpg"]
+ }
+ },
),
(
ChildFileUploadState,
{
- "state.file_state_base1.child_file_upload_state": {
+ ChildFileUploadState.get_full_name(): {
"img_list": ["image1.jpg", "image2.jpg"]
}
},
@@ -788,7 +747,7 @@ async def test_dict_mutation_detection__plain_list(
(
GrandChildFileUploadState,
{
- "state.file_state_base1.file_state_base2.grand_child_file_upload_state": {
+ GrandChildFileUploadState.get_full_name(): {
"img_list": ["image1.jpg", "image2.jpg"]
}
},
@@ -811,7 +770,8 @@ async def test_upload_file(tmp_path, state, delta, token: str, mocker):
)
state._tmp_path = tmp_path
# The App state must be the "root" of the state tree
- app = App(state=State)
+ app = App()
+ app._enable_state()
app.event_namespace.emit = AsyncMock() # type: ignore
current_state = await app.state_manager.get_state(_substate_key(token, state))
data = b"This is binary data"
@@ -914,7 +874,7 @@ async def test_upload_file_background(state, tmp_path, token):
await fn(request_mock, [file_mock])
assert (
err.value.args[0]
- == f"@rx.background is not supported for upload handler `{state.get_full_name()}.bg_upload`."
+ == f"@rx.event(background=True) is not supported for upload handler `{state.get_full_name()}.bg_upload`."
)
if isinstance(app.state_manager, StateManagerRedis):
@@ -945,11 +905,12 @@ class DynamicState(BaseState):
"""Event handler for page on_load, should trigger for all navigation events."""
self.loaded = self.loaded + 1
+ @rx.event
def on_counter(self):
"""Increment the counter var."""
self.counter = self.counter + 1
- @ComputedVar
+ @computed_var(cache=True)
def comp_dynamic(self) -> str:
"""A computed var that depends on the dynamic var.
@@ -962,9 +923,57 @@ class DynamicState(BaseState):
on_load_internal = OnLoadInternalState.on_load_internal.fn
+def test_dynamic_arg_shadow(
+ index_page: ComponentCallable,
+ windows_platform: bool,
+ token: str,
+ app_module_mock: unittest.mock.Mock,
+ mocker,
+):
+ """Create app with dynamic route var and try to add a page with a dynamic arg that shadows a state var.
+
+ Args:
+ index_page: The index page.
+ windows_platform: Whether the system is windows.
+ token: a Token.
+ app_module_mock: Mocked app module.
+ mocker: pytest mocker object.
+ """
+ arg_name = "counter"
+ route = f"/test/[{arg_name}]"
+ app = app_module_mock.app = App(state=DynamicState)
+ assert app.state is not None
+ with pytest.raises(NameError):
+ app.add_page(index_page, route=route, on_load=DynamicState.on_load) # type: ignore
+
+
+def test_multiple_dynamic_args(
+ index_page: ComponentCallable,
+ windows_platform: bool,
+ token: str,
+ app_module_mock: unittest.mock.Mock,
+ mocker,
+):
+ """Create app with multiple dynamic route vars with the same name.
+
+ Args:
+ index_page: The index page.
+ windows_platform: Whether the system is windows.
+ token: a Token.
+ app_module_mock: Mocked app module.
+ mocker: pytest mocker object.
+ """
+ arg_name = "my_arg"
+ route = f"/test/[{arg_name}]"
+ route2 = f"/test2/[{arg_name}]"
+ app = app_module_mock.app = App(state=EmptyState)
+ app.add_page(index_page, route=route)
+ app.add_page(index_page, route=route2)
+
+
@pytest.mark.asyncio
async def test_dynamic_route_var_route_change_completed_on_load(
- index_page,
+ index_page: ComponentCallable,
windows_platform: bool,
token: str,
app_module_mock: unittest.mock.Mock,
@@ -984,8 +993,6 @@ async def test_dynamic_route_var_route_change_completed_on_load(
"""
arg_name = "dynamic"
route = f"/test/[{arg_name}]"
- if windows_platform:
- route.lstrip("/").replace("/", "\\")
app = app_module_mock.app = App(state=DynamicState)
assert app.state is not None
assert arg_name not in app.state.vars
@@ -1061,7 +1068,7 @@ async def test_dynamic_route_var_route_change_completed_on_load(
val=exp_val,
),
_event(
- name="state.set_is_hydrated",
+ name=f"{State.get_name()}.set_is_hydrated",
payload={"value": True},
val=exp_val,
router_data={},
@@ -1092,9 +1099,6 @@ async def test_dynamic_route_var_route_change_completed_on_load(
assert on_load_update == StateUpdate(
delta={
state.get_name(): {
- # These computed vars _shouldn't_ be here, because they didn't change
- arg_name: exp_val,
- f"comp_{arg_name}": exp_val,
"loaded": exp_index + 1,
},
},
@@ -1116,9 +1120,6 @@ async def test_dynamic_route_var_route_change_completed_on_load(
assert on_set_is_hydrated_update == StateUpdate(
delta={
state.get_name(): {
- # These computed vars _shouldn't_ be here, because they didn't change
- arg_name: exp_val,
- f"comp_{arg_name}": exp_val,
"is_hydrated": True,
},
},
@@ -1140,9 +1141,6 @@ async def test_dynamic_route_var_route_change_completed_on_load(
assert update == StateUpdate(
delta={
state.get_name(): {
- # These computed vars _shouldn't_ be here, because they didn't change
- f"comp_{arg_name}": exp_val,
- arg_name: exp_val,
"counter": exp_index + 1,
}
},
@@ -1184,7 +1182,10 @@ async def test_process_events(mocker, token: str):
app = App(state=GenState)
mocker.patch.object(app, "_postprocess", AsyncMock())
event = Event(
- token=token, name="gen_state.go", payload={"c": 5}, router_data=router_data
+ token=token,
+ name=f"{GenState.get_name()}.go",
+ payload={"c": 5},
+ router_data=router_data,
)
async for _update in process(app, event, "mock_sid", {}, "127.0.0.1"):
@@ -1210,7 +1211,7 @@ async def test_process_events(mocker, token: str):
],
)
def test_overlay_component(
- state: State | None,
+ state: Type[State] | None,
overlay_component: Component | ComponentCallable | None,
exp_page_child: Type[Component] | None,
):
@@ -1242,6 +1243,7 @@ def test_overlay_component(
app.add_page(rx.box("Index"), route="/test")
# overlay components are wrapped during compile only
+ app._compile_page("test")
app._setup_overlay_component()
page = app.pages["test"]
@@ -1269,14 +1271,14 @@ def compilable_app(tmp_path) -> Generator[tuple[App, Path], None, None]:
app_path = tmp_path / "app"
web_dir = app_path / ".web"
web_dir.mkdir(parents=True)
- (web_dir / "package.json").touch()
+ (web_dir / constants.PackageJson.PATH).touch()
app = App(theme=None)
app._get_frontend_packages = unittest.mock.Mock()
with chdir(app_path):
yield app, web_dir
-def test_app_wrap_compile_theme(compilable_app):
+def test_app_wrap_compile_theme(compilable_app: tuple[App, Path]):
"""Test that the radix theme component wraps the app.
Args:
@@ -1293,7 +1295,7 @@ def test_app_wrap_compile_theme(compilable_app):
"function AppWrap({children}) {"
"return ("
""
- ""
+ ""
""
"{children}"
" "
@@ -1304,7 +1306,7 @@ def test_app_wrap_compile_theme(compilable_app):
) in "".join(app_js_lines)
-def test_app_wrap_priority(compilable_app):
+def test_app_wrap_priority(compilable_app: tuple[App, Path]):
"""Test that the app wrap components are wrapped in the correct order.
Args:
@@ -1316,13 +1318,13 @@ def test_app_wrap_priority(compilable_app):
tag = "Fragment1"
def _get_app_wrap_components(self) -> dict[tuple[int, str], Component]:
- return {(99, "Box"): rx.chakra.box()}
+ return {(99, "Box"): rx.box()}
class Fragment2(Component):
tag = "Fragment2"
def _get_app_wrap_components(self) -> dict[tuple[int, str], Component]:
- return {(50, "Text"): rx.chakra.text()}
+ return {(50, "Text"): rx.text()}
class Fragment3(Component):
tag = "Fragment3"
@@ -1342,19 +1344,17 @@ def test_app_wrap_priority(compilable_app):
assert (
"function AppWrap({children}) {"
"return ("
- ""
- ""
- ""
- ""
+ ""
+ ''
+ ""
""
""
"{children}"
" "
" "
- " "
- " "
- " "
- " "
+ " "
+ ""
+ ""
")"
"}"
) in "".join(app_js_lines)
@@ -1371,6 +1371,7 @@ def test_app_state_determination():
# Add a page with `on_load` enables state.
a1.add_page(rx.box("About"), route="/about", on_load=rx.console_log(""))
+ a1._compile_page("about")
assert a1.state is not None
a2 = App()
@@ -1378,6 +1379,7 @@ def test_app_state_determination():
# Referencing a state Var enables state.
a2.add_page(rx.box(rx.text(GenState.value)), route="/")
+ a2._compile_page("index")
assert a2.state is not None
a3 = App()
@@ -1385,23 +1387,22 @@ def test_app_state_determination():
# Referencing router enables state.
a3.add_page(rx.box(rx.text(State.router.page.full_path)), route="/")
+ a3._compile_page("index")
assert a3.state is not None
a4 = App()
assert a4.state is None
- # Referencing an event handler enables state.
a4.add_page(rx.box(rx.button("Click", on_click=rx.console_log(""))), route="/")
+ assert a4.state is None
+
+ a4.add_page(
+ rx.box(rx.button("Click", on_click=DynamicState.on_counter)), route="/page2"
+ )
+ a4._compile_page("page2")
assert a4.state is not None
-# for coverage
-def test_raise_on_connect_error():
- """Test that the connect_error function is called."""
- with pytest.raises(ValueError):
- App(connect_error_component="Foo")
-
-
def test_raise_on_state():
"""Test that the state is set."""
# state kwargs is deprecated, we just make sure the app is created anyway.
@@ -1432,7 +1433,9 @@ def test_app_state_manager():
app.state_manager
app._enable_state()
assert app.state_manager is not None
- assert isinstance(app.state_manager, (StateManagerMemory, StateManagerRedis))
+ assert isinstance(
+ app.state_manager, (StateManagerMemory, StateManagerDisk, StateManagerRedis)
+ )
def test_generate_component():
@@ -1469,22 +1472,25 @@ def test_add_page_component_returning_tuple():
app.add_page(index) # type: ignore
app.add_page(page2) # type: ignore
+ app._compile_page("index")
+ app._compile_page("page2")
+
assert isinstance((fragment_wrapper := app.pages["index"].children[0]), Fragment)
assert isinstance((first_text := fragment_wrapper.children[0]), Text)
- assert str(first_text.children[0].contents) == "{`first`}" # type: ignore
+ assert str(first_text.children[0].contents) == '"first"' # type: ignore
assert isinstance((second_text := fragment_wrapper.children[1]), Text)
- assert str(second_text.children[0].contents) == "{`second`}" # type: ignore
+ assert str(second_text.children[0].contents) == '"second"' # type: ignore
# Test page with trailing comma.
assert isinstance(
(page2_fragment_wrapper := app.pages["page2"].children[0]), Fragment
)
assert isinstance((third_text := page2_fragment_wrapper.children[0]), Text)
- assert str(third_text.children[0].contents) == "{`third`}" # type: ignore
+ assert str(third_text.children[0].contents) == '"third"' # type: ignore
@pytest.mark.parametrize("export", (True, False))
-def test_app_with_transpile_packages(compilable_app, export):
+def test_app_with_transpile_packages(compilable_app: tuple[App, Path], export: bool):
class C1(rx.Component):
library = "foo@1.2.3"
tag = "Foo"
@@ -1533,3 +1539,197 @@ def test_app_with_transpile_packages(compilable_app, export):
else:
assert 'output: "export"' not in next_config
assert f'distDir: "{constants.Dirs.STATIC}"' not in next_config
+
+
+def test_app_with_valid_var_dependencies(compilable_app: tuple[App, Path]):
+ app, _ = compilable_app
+
+ class ValidDepState(BaseState):
+ base: int = 0
+ _backend: int = 0
+
+ @computed_var(cache=True)
+ def foo(self) -> str:
+ return "foo"
+
+ @computed_var(deps=["_backend", "base", foo], cache=True)
+ def bar(self) -> str:
+ return "bar"
+
+ app.state = ValidDepState
+ app._compile()
+
+
+def test_app_with_invalid_var_dependencies(compilable_app: tuple[App, Path]):
+ app, _ = compilable_app
+
+ class InvalidDepState(BaseState):
+ @computed_var(deps=["foolksjdf"], cache=True)
+ def bar(self) -> str:
+ return "bar"
+
+ app.state = InvalidDepState
+ with pytest.raises(exceptions.VarDependencyError):
+ app._compile()
+
+
+# Test custom exception handlers
+
+
+def valid_custom_handler(exception: Exception, logger: str = "test"):
+ print("Custom Backend Exception")
+ print(exception)
+
+
+def custom_exception_handler_with_wrong_arg_order(
+ logger: str,
+ exception: Exception, # Should be first
+):
+ print("Custom Backend Exception")
+ print(exception)
+
+
+def custom_exception_handler_with_wrong_argspec(
+ exception: str, # Should be Exception
+):
+ print("Custom Backend Exception")
+ print(exception)
+
+
+class DummyExceptionHandler:
+ """Dummy exception handler class."""
+
+ def handle(self, exception: Exception):
+ """Handle the exception.
+
+ Args:
+ exception: The exception.
+
+ """
+ print("Custom Backend Exception")
+ print(exception)
+
+
+custom_exception_handlers = {
+ "lambda": lambda exception: print("Custom Exception Handler", exception),
+ "wrong_argspec": custom_exception_handler_with_wrong_argspec,
+ "wrong_arg_order": custom_exception_handler_with_wrong_arg_order,
+ "valid": valid_custom_handler,
+ "partial": functools.partial(valid_custom_handler, logger="test"),
+ "method": DummyExceptionHandler().handle,
+}
+
+
+@pytest.mark.parametrize(
+ "handler_fn, expected",
+ [
+ pytest.param(
+ custom_exception_handlers["partial"],
+ pytest.raises(ValueError),
+ id="partial",
+ ),
+ pytest.param(
+ custom_exception_handlers["lambda"],
+ pytest.raises(ValueError),
+ id="lambda",
+ ),
+ pytest.param(
+ custom_exception_handlers["wrong_argspec"],
+ pytest.raises(ValueError),
+ id="wrong_argspec",
+ ),
+ pytest.param(
+ custom_exception_handlers["wrong_arg_order"],
+ pytest.raises(ValueError),
+ id="wrong_arg_order",
+ ),
+ pytest.param(
+ custom_exception_handlers["valid"],
+ does_not_raise(),
+ id="valid_handler",
+ ),
+ pytest.param(
+ custom_exception_handlers["method"],
+ does_not_raise(),
+ id="valid_class_method",
+ ),
+ ],
+)
+def test_frontend_exception_handler_validation(handler_fn, expected):
+ """Test that the custom frontend exception handler is properly validated.
+
+ Args:
+ handler_fn: The handler function.
+ expected: The expected result.
+
+ """
+ with expected:
+ rx.App(frontend_exception_handler=handler_fn)._validate_exception_handlers()
+
+
+def backend_exception_handler_with_wrong_return_type(exception: Exception) -> int:
+ """Custom backend exception handler with wrong return type.
+
+ Args:
+ exception: The exception.
+
+ Returns:
+ int: The wrong return type.
+
+ """
+ print("Custom Backend Exception")
+ print(exception)
+
+ return 5
+
+
+@pytest.mark.parametrize(
+ "handler_fn, expected",
+ [
+ pytest.param(
+ backend_exception_handler_with_wrong_return_type,
+ pytest.raises(ValueError),
+ id="wrong_return_type",
+ ),
+ pytest.param(
+ custom_exception_handlers["partial"],
+ pytest.raises(ValueError),
+ id="partial",
+ ),
+ pytest.param(
+ custom_exception_handlers["lambda"],
+ pytest.raises(ValueError),
+ id="lambda",
+ ),
+ pytest.param(
+ custom_exception_handlers["wrong_argspec"],
+ pytest.raises(ValueError),
+ id="wrong_argspec",
+ ),
+ pytest.param(
+ custom_exception_handlers["wrong_arg_order"],
+ pytest.raises(ValueError),
+ id="wrong_arg_order",
+ ),
+ pytest.param(
+ custom_exception_handlers["valid"],
+ does_not_raise(),
+ id="valid_handler",
+ ),
+ pytest.param(
+ custom_exception_handlers["method"],
+ does_not_raise(),
+ id="valid_class_method",
+ ),
+ ],
+)
+def test_backend_exception_handler_validation(handler_fn, expected):
+ """Test that the custom backend exception handler is properly validated.
+
+ Args:
+ handler_fn: The handler function.
+ expected: The expected result.
+
+ """
+ with expected:
+ rx.App(backend_exception_handler=handler_fn)._validate_exception_handlers()
diff --git a/tests/test_attribute_access_type.py b/tests/units/test_attribute_access_type.py
similarity index 71%
rename from tests/test_attribute_access_type.py
rename to tests/units/test_attribute_access_type.py
index 821ccad04..0d490ec1e 100644
--- a/tests/test_attribute_access_type.py
+++ b/tests/units/test_attribute_access_type.py
@@ -1,10 +1,11 @@
from __future__ import annotations
-from typing import List, Optional, Union
+from typing import Dict, List, Optional, Type, Union
import attrs
import pytest
import sqlalchemy
+from sqlalchemy import JSON, TypeDecorator
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
@@ -12,10 +13,29 @@ import reflex as rx
from reflex.utils.types import GenericType, get_attribute_access_type
+class SQLAType(TypeDecorator):
+ """SQLAlchemy custom dict type."""
+
+ impl = JSON
+
+ @property
+ def python_type(self) -> Type[Dict[str, str]]:
+ """Python type.
+
+ Returns:
+ Python Type of the column.
+ """
+ return Dict[str, str]
+
+
class SQLABase(DeclarativeBase):
"""Base class for bare SQLAlchemy models."""
- pass
+ type_annotation_map = {
+ # do not use lower case dict here!
+ # https://github.com/sqlalchemy/sqlalchemy/issues/9902
+ Dict[str, str]: SQLAType,
+ }
class SQLATag(SQLABase):
@@ -52,6 +72,9 @@ class SQLAClass(SQLABase):
sqla_tag_id: Mapped[int] = mapped_column(sqlalchemy.ForeignKey(SQLATag.id))
sqla_tag: Mapped[Optional[SQLATag]] = relationship()
labels: Mapped[List[SQLALabel]] = relationship(back_populates="test")
+ # do not use lower case dict here!
+ # https://github.com/sqlalchemy/sqlalchemy/issues/9902
+ dict_str_str: Mapped[Dict[str, str]] = mapped_column()
@property
def str_property(self) -> str:
@@ -71,6 +94,15 @@ class SQLAClass(SQLABase):
"""
return self.name
+ @hybrid_property
+ def first_label(self) -> Optional[SQLALabel]:
+ """First label property.
+
+ Returns:
+ First label
+ """
+ return self.labels[0] if self.labels else None
+
class ModelClass(rx.Model):
"""Test reflex model."""
@@ -82,6 +114,7 @@ class ModelClass(rx.Model):
optional_int: Optional[int] = None
sqla_tag: Optional[SQLATag] = None
labels: List[SQLALabel] = []
+ dict_str_str: Dict[str, str] = {}
@property
def str_property(self) -> str:
@@ -101,6 +134,15 @@ class ModelClass(rx.Model):
"""
return self.name
+ @property
+ def first_label(self) -> Optional[SQLALabel]:
+ """First label property.
+
+ Returns:
+ First label
+ """
+ return self.labels[0] if self.labels else None
+
class BaseClass(rx.Base):
"""Test rx.Base class."""
@@ -112,6 +154,7 @@ class BaseClass(rx.Base):
optional_int: Optional[int] = None
sqla_tag: Optional[SQLATag] = None
labels: List[SQLALabel] = []
+ dict_str_str: Dict[str, str] = {}
@property
def str_property(self) -> str:
@@ -131,6 +174,15 @@ class BaseClass(rx.Base):
"""
return self.name
+ @property
+ def first_label(self) -> Optional[SQLALabel]:
+ """First label property.
+
+ Returns:
+ First label
+ """
+ return self.labels[0] if self.labels else None
+
class BareClass:
"""Bare python class."""
@@ -142,6 +194,7 @@ class BareClass:
optional_int: Optional[int] = None
sqla_tag: Optional[SQLATag] = None
labels: List[SQLALabel] = []
+ dict_str_str: Dict[str, str] = {}
@property
def str_property(self) -> str:
@@ -161,6 +214,15 @@ class BareClass:
"""
return self.name
+ @property
+ def first_label(self) -> Optional[SQLALabel]:
+ """First label property.
+
+ Returns:
+ First label
+ """
+ return self.labels[0] if self.labels else None
+
@attrs.define
class AttrClass:
@@ -173,6 +235,7 @@ class AttrClass:
optional_int: Optional[int] = None
sqla_tag: Optional[SQLATag] = None
labels: List[SQLALabel] = []
+ dict_str_str: Dict[str, str] = {}
@property
def str_property(self) -> str:
@@ -192,8 +255,25 @@ class AttrClass:
"""
return self.name
+ @property
+ def first_label(self) -> Optional[SQLALabel]:
+ """First label property.
-@pytest.fixture(params=[SQLAClass, BaseClass, BareClass, ModelClass, AttrClass])
+ Returns:
+ First label
+ """
+ return self.labels[0] if self.labels else None
+
+
+@pytest.fixture(
+ params=[
+ SQLAClass,
+ BaseClass,
+ BareClass,
+ ModelClass,
+ AttrClass,
+ ]
+)
def cls(request: pytest.FixtureRequest) -> type:
"""Fixture for the class to test.
@@ -216,8 +296,10 @@ def cls(request: pytest.FixtureRequest) -> type:
pytest.param("optional_int", Optional[int], id="Optional[int]"),
pytest.param("sqla_tag", Optional[SQLATag], id="Optional[SQLATag]"),
pytest.param("labels", List[SQLALabel], id="List[SQLALabel]"),
+ pytest.param("dict_str_str", Dict[str, str], id="Dict[str, str]"),
pytest.param("str_property", str, id="str_property"),
pytest.param("str_or_int_property", Union[str, int], id="str_or_int_property"),
+ pytest.param("first_label", Optional[SQLALabel], id="first_label"),
],
)
def test_get_attribute_access_type(cls: type, attr: str, expected: GenericType) -> None:
diff --git a/tests/test_base.py b/tests/units/test_base.py
similarity index 100%
rename from tests/test_base.py
rename to tests/units/test_base.py
diff --git a/tests/test_config.py b/tests/units/test_config.py
similarity index 76%
rename from tests/test_config.py
rename to tests/units/test_config.py
index 31dd77649..0c63abc96 100644
--- a/tests/test_config.py
+++ b/tests/units/test_config.py
@@ -1,11 +1,19 @@
import multiprocessing
import os
+from pathlib import Path
+from typing import Any, Dict
import pytest
import reflex as rx
import reflex.config
-from reflex.constants import Endpoint
+from reflex.config import (
+ environment,
+ interpret_boolean_env,
+ interpret_enum_env,
+ interpret_int_env,
+)
+from reflex.constants import Endpoint, Env
def test_requires_app_name():
@@ -41,7 +49,12 @@ def test_set_app_name(base_config_values):
("TELEMETRY_ENABLED", True),
],
)
-def test_update_from_env(base_config_values, monkeypatch, env_var, value):
+def test_update_from_env(
+ base_config_values: Dict[str, Any],
+ monkeypatch: pytest.MonkeyPatch,
+ env_var: str,
+ value: Any,
+):
"""Test that environment variables override config values.
Args:
@@ -56,6 +69,29 @@ def test_update_from_env(base_config_values, monkeypatch, env_var, value):
assert getattr(config, env_var.lower()) == value
+def test_update_from_env_path(
+ base_config_values: Dict[str, Any],
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+):
+ """Test that environment variables override config values.
+
+ Args:
+ base_config_values: Config values.
+ monkeypatch: The pytest monkeypatch object.
+ tmp_path: The pytest tmp_path fixture object.
+ """
+ monkeypatch.setenv("BUN_PATH", "/test")
+ assert os.environ.get("BUN_PATH") == "/test"
+ with pytest.raises(ValueError):
+ rx.Config(**base_config_values)
+
+ monkeypatch.setenv("BUN_PATH", str(tmp_path))
+ assert os.environ.get("BUN_PATH") == str(tmp_path)
+ config = rx.Config(**base_config_values)
+ assert config.bun_path == tmp_path
+
+
@pytest.mark.parametrize(
"kwargs, expected",
[
@@ -177,11 +213,11 @@ def test_replace_defaults(
assert getattr(c, key) == value
-def reflex_dir_constant():
- return rx.constants.Reflex.DIR
+def reflex_dir_constant() -> Path:
+ return environment.REFLEX_DIR
-def test_reflex_dir_env_var(monkeypatch, tmp_path):
+def test_reflex_dir_env_var(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
"""Test that the REFLEX_DIR environment variable is used to set the Reflex.DIR constant.
Args:
@@ -192,4 +228,17 @@ def test_reflex_dir_env_var(monkeypatch, tmp_path):
mp_ctx = multiprocessing.get_context(method="spawn")
with mp_ctx.Pool(processes=1) as pool:
- assert pool.apply(reflex_dir_constant) == str(tmp_path)
+ assert pool.apply(reflex_dir_constant) == tmp_path
+
+
+def test_interpret_enum_env() -> None:
+ assert interpret_enum_env(Env.PROD.value, Env, "REFLEX_ENV") == Env.PROD
+
+
+def test_interpret_int_env() -> None:
+ assert interpret_int_env("3001", "FRONTEND_PORT") == 3001
+
+
+@pytest.mark.parametrize("value, expected", [("true", True), ("false", False)])
+def test_interpret_bool_env(value: str, expected: bool) -> None:
+ assert interpret_boolean_env(value, "TELEMETRY_ENABLED") == expected
diff --git a/tests/test_db_config.py b/tests/units/test_db_config.py
similarity index 100%
rename from tests/test_db_config.py
rename to tests/units/test_db_config.py
diff --git a/tests/test_event.py b/tests/units/test_event.py
similarity index 64%
rename from tests/test_event.py
rename to tests/units/test_event.py
index 885263157..d7b7cf7a2 100644
--- a/tests/test_event.py
+++ b/tests/units/test_event.py
@@ -1,13 +1,19 @@
-import json
from typing import List
import pytest
-from reflex import event
-from reflex.event import Event, EventHandler, EventSpec, call_event_handler, fix_events
+from reflex.event import (
+ Event,
+ EventChain,
+ EventHandler,
+ EventSpec,
+ call_event_handler,
+ event,
+ fix_events,
+)
from reflex.state import BaseState
from reflex.utils import format
-from reflex.vars import Var
+from reflex.vars.base import Field, LiteralVar, Var, field
def make_var(value) -> Var:
@@ -19,9 +25,7 @@ def make_var(value) -> Var:
Returns:
The var.
"""
- var = Var.create(value)
- assert var is not None
- return var
+ return Var(_js_expr=value)
def test_create_event():
@@ -57,10 +61,10 @@ def test_call_event_handler():
# Test passing vars as args.
assert event_spec.handler == handler
- assert event_spec.args[0][0].equals(Var.create_safe("arg1"))
- assert event_spec.args[0][1].equals(Var.create_safe("first"))
- assert event_spec.args[1][0].equals(Var.create_safe("arg2"))
- assert event_spec.args[1][1].equals(Var.create_safe("second"))
+ assert event_spec.args[0][0].equals(Var(_js_expr="arg1"))
+ assert event_spec.args[0][1].equals(Var(_js_expr="first"))
+ assert event_spec.args[1][0].equals(Var(_js_expr="arg2"))
+ assert event_spec.args[1][1].equals(Var(_js_expr="second"))
assert (
format.format_event(event_spec)
== 'Event("test_fn_with_args", {arg1:first,arg2:second})'
@@ -70,7 +74,7 @@ def test_call_event_handler():
event_spec = handler("first", "second") # type: ignore
assert (
format.format_event(event_spec)
- == 'Event("test_fn_with_args", {arg1:`first`,arg2:`second`})'
+ == 'Event("test_fn_with_args", {arg1:"first",arg2:"second"})'
)
first, second = 123, "456"
@@ -78,14 +82,14 @@ def test_call_event_handler():
event_spec = handler(first, second) # type: ignore
assert (
format.format_event(event_spec)
- == 'Event("test_fn_with_args", {arg1:123,arg2:`456`})'
+ == 'Event("test_fn_with_args", {arg1:123,arg2:"456"})'
)
assert event_spec.handler == handler
- assert event_spec.args[0][0].equals(Var.create_safe("arg1"))
- assert event_spec.args[0][1].equals(Var.create_safe(first))
- assert event_spec.args[1][0].equals(Var.create_safe("arg2"))
- assert event_spec.args[1][1].equals(Var.create_safe(second))
+ assert event_spec.args[0][0].equals(Var(_js_expr="arg1"))
+ assert event_spec.args[0][1].equals(LiteralVar.create(first))
+ assert event_spec.args[1][0].equals(Var(_js_expr="arg2"))
+ assert event_spec.args[1][1].equals(LiteralVar.create(second))
handler = EventHandler(fn=test_fn_with_args)
with pytest.raises(TypeError):
@@ -100,7 +104,7 @@ def test_call_event_handler_partial():
test_fn_with_args.__qualname__ = "test_fn_with_args"
- def spec(a2: str) -> List[str]:
+ def spec(a2: Var[str]) -> List[Var[str]]:
return [a2]
handler = EventHandler(fn=test_fn_with_args)
@@ -109,17 +113,17 @@ def test_call_event_handler_partial():
assert event_spec.handler == handler
assert len(event_spec.args) == 1
- assert event_spec.args[0][0].equals(Var.create_safe("arg1"))
- assert event_spec.args[0][1].equals(Var.create_safe("first"))
+ assert event_spec.args[0][0].equals(Var(_js_expr="arg1"))
+ assert event_spec.args[0][1].equals(Var(_js_expr="first"))
assert format.format_event(event_spec) == 'Event("test_fn_with_args", {arg1:first})'
assert event_spec2 is not event_spec
assert event_spec2.handler == handler
assert len(event_spec2.args) == 2
- assert event_spec2.args[0][0].equals(Var.create_safe("arg1"))
- assert event_spec2.args[0][1].equals(Var.create_safe("first"))
- assert event_spec2.args[1][0].equals(Var.create_safe("arg2"))
- assert event_spec2.args[1][1].equals(Var.create_safe("_a2"))
+ assert event_spec2.args[0][0].equals(Var(_js_expr="arg1"))
+ assert event_spec2.args[0][1].equals(Var(_js_expr="first"))
+ assert event_spec2.args[1][0].equals(Var(_js_expr="arg2"))
+ assert event_spec2.args[1][1].equals(Var(_js_expr="_a2", _var_type=str))
assert (
format.format_event(event_spec2)
== 'Event("test_fn_with_args", {arg1:first,arg2:_a2})'
@@ -158,12 +162,29 @@ def test_fix_events(arg1, arg2):
@pytest.mark.parametrize(
"input,output",
[
- (("/path", None), 'Event("_redirect", {path:`/path`,external:false})'),
- (("/path", True), 'Event("_redirect", {path:`/path`,external:true})'),
- (("/path", False), 'Event("_redirect", {path:`/path`,external:false})'),
(
- (Var.create_safe("path"), None),
- 'Event("_redirect", {path:path,external:false})',
+ ("/path", None, None),
+ 'Event("_redirect", {path:"/path",external:false,replace:false})',
+ ),
+ (
+ ("/path", True, None),
+ 'Event("_redirect", {path:"/path",external:true,replace:false})',
+ ),
+ (
+ ("/path", False, None),
+ 'Event("_redirect", {path:"/path",external:false,replace:false})',
+ ),
+ (
+ (Var(_js_expr="path"), None, None),
+ 'Event("_redirect", {path:path,external:false,replace:false})',
+ ),
+ (
+ ("/path", None, True),
+ 'Event("_redirect", {path:"/path",external:false,replace:true})',
+ ),
+ (
+ ("/path", True, True),
+ 'Event("_redirect", {path:"/path",external:true,replace:true})',
),
],
)
@@ -174,17 +195,19 @@ def test_event_redirect(input, output):
input: The input for running the test.
output: The expected output to validate the test.
"""
- path, external = input
- if external is None:
- spec = event.redirect(path)
- else:
- spec = event.redirect(path, external=external)
+ path, external, replace = input
+ kwargs = {}
+ if external is not None:
+ kwargs["external"] = external
+ if replace is not None:
+ kwargs["replace"] = replace
+ spec = event.redirect(path, **kwargs)
assert isinstance(spec, EventSpec)
assert spec.handler.fn.__qualname__ == "_redirect"
# this asserts need comment about what it's testing (they fail with Var as input)
- # assert spec.args[0][0].equals(Var.create_safe("path"))
- # assert spec.args[0][1].equals(Var.create_safe("/path"))
+ # assert spec.args[0][0].equals(Var(_js_expr="path"))
+ # assert spec.args[0][1].equals(Var(_js_expr="/path"))
assert format.format_event(spec) == output
@@ -194,10 +217,10 @@ def test_event_console_log():
spec = event.console_log("message")
assert isinstance(spec, EventSpec)
assert spec.handler.fn.__qualname__ == "_console"
- assert spec.args[0][0].equals(Var.create_safe("message"))
- assert spec.args[0][1].equals(Var.create_safe("message"))
- assert format.format_event(spec) == 'Event("_console", {message:`message`})'
- spec = event.console_log(Var.create_safe("message"))
+ assert spec.args[0][0].equals(Var(_js_expr="message"))
+ assert spec.args[0][1].equals(LiteralVar.create("message"))
+ assert format.format_event(spec) == 'Event("_console", {message:"message"})'
+ spec = event.console_log(Var(_js_expr="message"))
assert format.format_event(spec) == 'Event("_console", {message:message})'
@@ -206,10 +229,10 @@ def test_event_window_alert():
spec = event.window_alert("message")
assert isinstance(spec, EventSpec)
assert spec.handler.fn.__qualname__ == "_alert"
- assert spec.args[0][0].equals(Var.create_safe("message"))
- assert spec.args[0][1].equals(Var.create_safe("message"))
- assert format.format_event(spec) == 'Event("_alert", {message:`message`})'
- spec = event.window_alert(Var.create_safe("message"))
+ assert spec.args[0][0].equals(Var(_js_expr="message"))
+ assert spec.args[0][1].equals(LiteralVar.create("message"))
+ assert format.format_event(spec) == 'Event("_alert", {message:"message"})'
+ spec = event.window_alert(Var(_js_expr="message"))
assert format.format_event(spec) == 'Event("_alert", {message:message})'
@@ -218,11 +241,11 @@ def test_set_focus():
spec = event.set_focus("input1")
assert isinstance(spec, EventSpec)
assert spec.handler.fn.__qualname__ == "_set_focus"
- assert spec.args[0][0].equals(Var.create_safe("ref"))
- assert spec.args[0][1].equals(Var.create_safe("ref_input1"))
- assert format.format_event(spec) == 'Event("_set_focus", {ref:`ref_input1`})'
+ assert spec.args[0][0].equals(Var(_js_expr="ref"))
+ assert spec.args[0][1].equals(LiteralVar.create("ref_input1"))
+ assert format.format_event(spec) == 'Event("_set_focus", {ref:"ref_input1"})'
spec = event.set_focus("input1")
- assert format.format_event(spec) == 'Event("_set_focus", {ref:`ref_input1`})'
+ assert format.format_event(spec) == 'Event("_set_focus", {ref:"ref_input1"})'
def test_set_value():
@@ -230,17 +253,17 @@ def test_set_value():
spec = event.set_value("input1", "")
assert isinstance(spec, EventSpec)
assert spec.handler.fn.__qualname__ == "_set_value"
- assert spec.args[0][0].equals(Var.create_safe("ref"))
- assert spec.args[0][1].equals(Var.create_safe("ref_input1"))
- assert spec.args[1][0].equals(Var.create_safe("value"))
- assert spec.args[1][1].equals(Var.create_safe(""))
+ assert spec.args[0][0].equals(Var(_js_expr="ref"))
+ assert spec.args[0][1].equals(LiteralVar.create("ref_input1"))
+ assert spec.args[1][0].equals(Var(_js_expr="value"))
+ assert spec.args[1][1].equals(LiteralVar.create(""))
assert (
- format.format_event(spec) == 'Event("_set_value", {ref:`ref_input1`,value:``})'
+ format.format_event(spec) == 'Event("_set_value", {ref:"ref_input1",value:""})'
)
- spec = event.set_value("input1", Var.create_safe("message"))
+ spec = event.set_value("input1", Var(_js_expr="message"))
assert (
format.format_event(spec)
- == 'Event("_set_value", {ref:`ref_input1`,value:message})'
+ == 'Event("_set_value", {ref:"ref_input1",value:message})'
)
@@ -249,13 +272,13 @@ def test_remove_cookie():
spec = event.remove_cookie("testkey")
assert isinstance(spec, EventSpec)
assert spec.handler.fn.__qualname__ == "_remove_cookie"
- assert spec.args[0][0].equals(Var.create_safe("key"))
- assert spec.args[0][1].equals(Var.create_safe("testkey"))
- assert spec.args[1][0].equals(Var.create_safe("options"))
- assert spec.args[1][1].equals(Var.create_safe({"path": "/"}))
+ assert spec.args[0][0].equals(Var(_js_expr="key"))
+ assert spec.args[0][1].equals(LiteralVar.create("testkey"))
+ assert spec.args[1][0].equals(Var(_js_expr="options"))
+ assert spec.args[1][1].equals(LiteralVar.create({"path": "/"}))
assert (
format.format_event(spec)
- == 'Event("_remove_cookie", {key:`testkey`,options:{"path": "/"}})'
+ == 'Event("_remove_cookie", {key:"testkey",options:({ ["path"] : "/" })})'
)
@@ -270,13 +293,13 @@ def test_remove_cookie_with_options():
spec = event.remove_cookie("testkey", options)
assert isinstance(spec, EventSpec)
assert spec.handler.fn.__qualname__ == "_remove_cookie"
- assert spec.args[0][0].equals(Var.create_safe("key"))
- assert spec.args[0][1].equals(Var.create_safe("testkey"))
- assert spec.args[1][0].equals(Var.create_safe("options"))
- assert spec.args[1][1].equals(Var.create_safe(options))
+ assert spec.args[0][0].equals(Var(_js_expr="key"))
+ assert spec.args[0][1].equals(LiteralVar.create("testkey"))
+ assert spec.args[1][0].equals(Var(_js_expr="options"))
+ assert spec.args[1][1].equals(LiteralVar.create(options))
assert (
format.format_event(spec)
- == f'Event("_remove_cookie", {{key:`testkey`,options:{json.dumps(options)}}})'
+ == f'Event("_remove_cookie", {{key:"testkey",options:{str(LiteralVar.create(options))}}})'
)
@@ -294,10 +317,10 @@ def test_remove_local_storage():
spec = event.remove_local_storage("testkey")
assert isinstance(spec, EventSpec)
assert spec.handler.fn.__qualname__ == "_remove_local_storage"
- assert spec.args[0][0].equals(Var.create_safe("key"))
- assert spec.args[0][1].equals(Var.create_safe("testkey"))
+ assert spec.args[0][0].equals(Var(_js_expr="key"))
+ assert spec.args[0][1].equals(LiteralVar.create("testkey"))
assert (
- format.format_event(spec) == 'Event("_remove_local_storage", {key:`testkey`})'
+ format.format_event(spec) == 'Event("_remove_local_storage", {key:"testkey"})'
)
@@ -372,3 +395,28 @@ def test_event_actions_on_state():
assert sp_handler.event_actions == {"stopPropagation": True}
# should NOT affect other references to the handler
assert not handler.event_actions
+
+
+def test_event_var_data():
+ class S(BaseState):
+ x: Field[int] = field(0)
+
+ @event
+ def s(self, value: int):
+ pass
+
+ # Handler doesn't have any _var_data because it's just a str
+ handler_var = Var.create(S.s)
+ assert handler_var._get_all_var_data() is None
+
+ # Ensure spec carries _var_data
+ spec_var = Var.create(S.s(S.x))
+ assert spec_var._get_all_var_data() == S.x._get_all_var_data()
+
+ # Needed to instantiate the EventChain
+ def _args_spec(value: Var[int]) -> tuple[Var[int]]:
+ return (value,)
+
+ # Ensure chain carries _var_data
+ chain_var = Var.create(EventChain(events=[S.s(S.x)], args_spec=_args_spec))
+ assert chain_var._get_all_var_data() == S.x._get_all_var_data()
diff --git a/tests/units/test_health_endpoint.py b/tests/units/test_health_endpoint.py
new file mode 100644
index 000000000..fe350266f
--- /dev/null
+++ b/tests/units/test_health_endpoint.py
@@ -0,0 +1,106 @@
+import json
+from unittest.mock import MagicMock, Mock
+
+import pytest
+import sqlalchemy
+from redis.exceptions import RedisError
+
+from reflex.app import health
+from reflex.model import get_db_status
+from reflex.utils.prerequisites import get_redis_status
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ "mock_redis_client, expected_status",
+ [
+ # Case 1: Redis client is available and responds to ping
+ (Mock(ping=lambda: None), True),
+ # Case 2: Redis client raises RedisError
+ (Mock(ping=lambda: (_ for _ in ()).throw(RedisError)), False),
+ # Case 3: Redis client is not used
+ (None, None),
+ ],
+)
+async def test_get_redis_status(mock_redis_client, expected_status, mocker):
+ # Mock the `get_redis_sync` function to return the mock Redis client
+ mock_get_redis_sync = mocker.patch(
+ "reflex.utils.prerequisites.get_redis_sync", return_value=mock_redis_client
+ )
+
+ # Call the function
+ status = await get_redis_status()
+
+ # Verify the result
+ assert status == expected_status
+ mock_get_redis_sync.assert_called_once()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ "mock_engine, execute_side_effect, expected_status",
+ [
+ # Case 1: Database is accessible
+ (MagicMock(), None, True),
+ # Case 2: Database connection error (OperationalError)
+ (
+ MagicMock(),
+ sqlalchemy.exc.OperationalError("error", "error", "error"),
+ False,
+ ),
+ ],
+)
+async def test_get_db_status(mock_engine, execute_side_effect, expected_status, mocker):
+ # Mock get_engine to return the mock_engine
+ mock_get_engine = mocker.patch("reflex.model.get_engine", return_value=mock_engine)
+
+ # Mock the connection and its execute method
+ if mock_engine:
+ mock_connection = mock_engine.connect.return_value.__enter__.return_value
+ if execute_side_effect:
+ # Simulate execute method raising an exception
+ mock_connection.execute.side_effect = execute_side_effect
+ else:
+ # Simulate successful execute call
+ mock_connection.execute.return_value = None
+
+ # Call the function
+ status = await get_db_status()
+
+ # Verify the result
+ assert status == expected_status
+ mock_get_engine.assert_called_once()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ "db_status, redis_status, expected_status, expected_code",
+ [
+ # Case 1: Both services are connected
+ (True, True, {"status": True, "db": True, "redis": True}, 200),
+ # Case 2: Database not connected, Redis connected
+ (False, True, {"status": False, "db": False, "redis": True}, 503),
+ # Case 3: Database connected, Redis not connected
+ (True, False, {"status": False, "db": True, "redis": False}, 503),
+ # Case 4: Both services not connected
+ (False, False, {"status": False, "db": False, "redis": False}, 503),
+ # Case 5: Database Connected, Redis not used
+ (True, None, {"status": True, "db": True, "redis": False}, 200),
+ ],
+)
+async def test_health(db_status, redis_status, expected_status, expected_code, mocker):
+ # Mock get_db_status and get_redis_status
+ mocker.patch("reflex.app.get_db_status", return_value=db_status)
+ mocker.patch(
+ "reflex.utils.prerequisites.get_redis_status", return_value=redis_status
+ )
+
+ # Call the async health function
+ response = await health()
+
+ print(json.loads(response.body))
+ print(expected_status)
+
+ # Verify the response content and status code
+ assert response.status_code == expected_code
+ assert json.loads(response.body) == expected_status
diff --git a/tests/test_model.py b/tests/units/test_model.py
similarity index 81%
rename from tests/test_model.py
rename to tests/units/test_model.py
index ee0336b37..ac8187e03 100644
--- a/tests/test_model.py
+++ b/tests/units/test_model.py
@@ -1,4 +1,5 @@
-from typing import Optional
+from pathlib import Path
+from typing import Optional, Type
from unittest import mock
import pytest
@@ -7,7 +8,7 @@ import sqlmodel
import reflex.constants
import reflex.model
-from reflex.model import Model
+from reflex.model import Model, ModelRegistry
@pytest.fixture
@@ -39,7 +40,7 @@ def model_custom_primary() -> Model:
return ChildModel(name="name")
-def test_default_primary_key(model_default_primary):
+def test_default_primary_key(model_default_primary: Model):
"""Test that if a primary key is not defined a default is added.
Args:
@@ -48,7 +49,7 @@ def test_default_primary_key(model_default_primary):
assert "id" in model_default_primary.__class__.__fields__
-def test_custom_primary_key(model_custom_primary):
+def test_custom_primary_key(model_custom_primary: Model):
"""Test that if a primary key is defined no default key is added.
Args:
@@ -60,12 +61,17 @@ def test_custom_primary_key(model_custom_primary):
@pytest.mark.filterwarnings(
"ignore:This declarative base already contains a class with the same class name",
)
-def test_automigration(tmp_working_dir, monkeypatch):
+def test_automigration(
+ tmp_working_dir: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ model_registry: Type[ModelRegistry],
+):
"""Test alembic automigration with add and drop table and column.
Args:
tmp_working_dir: directory where database and migrations are stored
monkeypatch: pytest fixture to overwrite attributes
+ model_registry: clean reflex ModelRegistry
"""
alembic_ini = tmp_working_dir / "alembic.ini"
versions = tmp_working_dir / "alembic" / "versions"
@@ -84,8 +90,10 @@ def test_automigration(tmp_working_dir, monkeypatch):
t1: str
with Model.get_db_engine().connect() as connection:
- Model.alembic_autogenerate(connection=connection, message="Initial Revision")
- Model.migrate()
+ assert Model.alembic_autogenerate(
+ connection=connection, message="Initial Revision"
+ )
+ assert Model.migrate()
version_scripts = list(versions.glob("*.py"))
assert len(version_scripts) == 1
assert version_scripts[0].name.endswith("initial_revision.py")
@@ -94,14 +102,14 @@ def test_automigration(tmp_working_dir, monkeypatch):
session.add(AlembicThing(id=None, t1="foo"))
session.commit()
- sqlmodel.SQLModel.metadata.clear()
+ model_registry.get_metadata().clear()
# Create column t2, mark t1 as optional with default
class AlembicThing(Model, table=True): # type: ignore
t1: Optional[str] = "default"
t2: str = "bar"
- Model.migrate(autogenerate=True)
+ assert Model.migrate(autogenerate=True)
assert len(list(versions.glob("*.py"))) == 2
with reflex.model.session() as session:
@@ -114,13 +122,13 @@ def test_automigration(tmp_working_dir, monkeypatch):
assert result[1].t1 == "default"
assert result[1].t2 == "baz"
- sqlmodel.SQLModel.metadata.clear()
+ model_registry.get_metadata().clear()
# Drop column t1
class AlembicThing(Model, table=True): # type: ignore
t2: str = "bar"
- Model.migrate(autogenerate=True)
+ assert Model.migrate(autogenerate=True)
assert len(list(versions.glob("*.py"))) == 3
with reflex.model.session() as session:
@@ -134,7 +142,7 @@ def test_automigration(tmp_working_dir, monkeypatch):
a: int = 42
b: float = 4.2
- Model.migrate(autogenerate=True)
+ assert Model.migrate(autogenerate=True)
assert len(list(versions.glob("*.py"))) == 4
with reflex.model.session() as session:
@@ -146,16 +154,16 @@ def test_automigration(tmp_working_dir, monkeypatch):
assert result[0].b == 4.2
# No-op
- Model.migrate(autogenerate=True)
+ assert Model.migrate(autogenerate=True)
assert len(list(versions.glob("*.py"))) == 4
# drop table (AlembicSecond)
- sqlmodel.SQLModel.metadata.clear()
+ model_registry.get_metadata().clear()
class AlembicThing(Model, table=True): # type: ignore
t2: str = "bar"
- Model.migrate(autogenerate=True)
+ assert Model.migrate(autogenerate=True)
assert len(list(versions.glob("*.py"))) == 5
with reflex.model.session() as session:
@@ -168,18 +176,18 @@ def test_automigration(tmp_working_dir, monkeypatch):
assert result[0].t2 == "bar"
assert result[1].t2 == "baz"
- sqlmodel.SQLModel.metadata.clear()
+ model_registry.get_metadata().clear()
class AlembicThing(Model, table=True): # type: ignore
# changing column type not supported by default
t2: int = 42
- Model.migrate(autogenerate=True)
+ assert Model.migrate(autogenerate=True)
assert len(list(versions.glob("*.py"))) == 5
# clear all metadata to avoid influencing subsequent tests
- sqlmodel.SQLModel.metadata.clear()
+ model_registry.get_metadata().clear()
# drop remaining tables
- Model.migrate(autogenerate=True)
+ assert Model.migrate(autogenerate=True)
assert len(list(versions.glob("*.py"))) == 6
diff --git a/tests/units/test_page.py b/tests/units/test_page.py
new file mode 100644
index 000000000..e1dd70905
--- /dev/null
+++ b/tests/units/test_page.py
@@ -0,0 +1,79 @@
+from reflex import text
+from reflex.config import get_config
+from reflex.page import DECORATED_PAGES, get_decorated_pages, page
+
+
+def test_page_decorator():
+ def foo_():
+ return text("foo")
+
+ assert len(DECORATED_PAGES) == 0
+ decorated_foo_ = page()(foo_)
+ assert decorated_foo_ == foo_
+ assert len(DECORATED_PAGES) == 1
+ page_data = DECORATED_PAGES.get(get_config().app_name, [])[0][1]
+ assert page_data == {}
+ DECORATED_PAGES.clear()
+
+
+def test_page_decorator_with_kwargs():
+ def foo_():
+ return text("foo")
+
+ def load_foo():
+ return []
+
+ DECORATED_PAGES.clear()
+ assert len(DECORATED_PAGES) == 0
+ decorated_foo_ = page(
+ route="foo",
+ title="Foo",
+ image="foo.png",
+ description="Foo description",
+ meta=["foo-meta"],
+ script_tags=["foo-script"],
+ on_load=load_foo,
+ )(foo_)
+ assert decorated_foo_ == foo_
+ assert len(DECORATED_PAGES) == 1
+ page_data = DECORATED_PAGES.get(get_config().app_name, [])[0][1]
+ assert page_data == {
+ "description": "Foo description",
+ "image": "foo.png",
+ "meta": ["foo-meta"],
+ "on_load": load_foo,
+ "route": "foo",
+ "script_tags": ["foo-script"],
+ "title": "Foo",
+ }
+
+ DECORATED_PAGES.clear()
+
+
+def test_get_decorated_pages():
+ assert get_decorated_pages() == []
+
+ def foo_():
+ return text("foo")
+
+ page()(foo_)
+
+ assert get_decorated_pages() == []
+ assert get_decorated_pages(omit_implicit_routes=False) == [{}]
+
+ page(route="foo2")(foo_)
+
+ assert get_decorated_pages() == [{"route": "foo2"}]
+ assert get_decorated_pages(omit_implicit_routes=False) == [{}, {"route": "foo2"}]
+
+ page(route="foo3", title="Foo3")(foo_)
+
+ assert get_decorated_pages() == [
+ {"route": "foo2"},
+ {"route": "foo3", "title": "Foo3"},
+ ]
+ assert get_decorated_pages(omit_implicit_routes=False) == [
+ {},
+ {"route": "foo2"},
+ {"route": "foo3", "title": "Foo3"},
+ ]
diff --git a/tests/test_prerequisites.py b/tests/units/test_prerequisites.py
similarity index 90%
rename from tests/test_prerequisites.py
rename to tests/units/test_prerequisites.py
index c4f57a998..2497318e7 100644
--- a/tests/test_prerequisites.py
+++ b/tests/units/test_prerequisites.py
@@ -24,7 +24,15 @@ from reflex.utils.prerequisites import (
app_name="test",
),
False,
- 'module.exports = {basePath: "", compress: true, reactStrictMode: true, trailingSlash: true};',
+ 'module.exports = {basePath: "", compress: true, reactStrictMode: true, trailingSlash: true, staticPageGenerationTimeout: 60};',
+ ),
+ (
+ Config(
+ app_name="test",
+ static_page_generation_timeout=30,
+ ),
+ False,
+ 'module.exports = {basePath: "", compress: true, reactStrictMode: true, trailingSlash: true, staticPageGenerationTimeout: 30};',
),
(
Config(
@@ -32,7 +40,7 @@ from reflex.utils.prerequisites import (
next_compression=False,
),
False,
- 'module.exports = {basePath: "", compress: false, reactStrictMode: true, trailingSlash: true};',
+ 'module.exports = {basePath: "", compress: false, reactStrictMode: true, trailingSlash: true, staticPageGenerationTimeout: 60};',
),
(
Config(
@@ -40,7 +48,7 @@ from reflex.utils.prerequisites import (
frontend_path="/test",
),
False,
- 'module.exports = {basePath: "/test", compress: true, reactStrictMode: true, trailingSlash: true};',
+ 'module.exports = {basePath: "/test", compress: true, reactStrictMode: true, trailingSlash: true, staticPageGenerationTimeout: 60};',
),
(
Config(
@@ -49,14 +57,14 @@ from reflex.utils.prerequisites import (
next_compression=False,
),
False,
- 'module.exports = {basePath: "/test", compress: false, reactStrictMode: true, trailingSlash: true};',
+ 'module.exports = {basePath: "/test", compress: false, reactStrictMode: true, trailingSlash: true, staticPageGenerationTimeout: 60};',
),
(
Config(
app_name="test",
),
True,
- 'module.exports = {basePath: "", compress: true, reactStrictMode: true, trailingSlash: true, output: "export", distDir: "_static"};',
+ 'module.exports = {basePath: "", compress: true, reactStrictMode: true, trailingSlash: true, staticPageGenerationTimeout: 60, output: "export", distDir: "_static"};',
),
],
)
diff --git a/tests/test_route.py b/tests/units/test_route.py
similarity index 100%
rename from tests/test_route.py
rename to tests/units/test_route.py
diff --git a/tests/units/test_sqlalchemy.py b/tests/units/test_sqlalchemy.py
new file mode 100644
index 000000000..b18799e0c
--- /dev/null
+++ b/tests/units/test_sqlalchemy.py
@@ -0,0 +1,166 @@
+from pathlib import Path
+from typing import Optional, Type
+from unittest import mock
+
+import pytest
+from sqlalchemy import select
+from sqlalchemy.exc import OperationalError
+from sqlalchemy.orm import (
+ DeclarativeBase,
+ Mapped,
+ MappedAsDataclass,
+ declared_attr,
+ mapped_column,
+)
+
+import reflex.constants
+import reflex.model
+from reflex.model import Model, ModelRegistry, sqla_session
+
+
+@pytest.mark.filterwarnings(
+ "ignore:This declarative base already contains a class with the same class name",
+)
+def test_automigration(
+ tmp_working_dir: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ model_registry: Type[ModelRegistry],
+):
+ """Test alembic automigration with add and drop table and column.
+
+ Args:
+ tmp_working_dir: directory where database and migrations are stored
+ monkeypatch: pytest fixture to overwrite attributes
+ model_registry: clean reflex ModelRegistry
+ """
+ alembic_ini = tmp_working_dir / "alembic.ini"
+ versions = tmp_working_dir / "alembic" / "versions"
+ monkeypatch.setattr(reflex.constants, "ALEMBIC_CONFIG", str(alembic_ini))
+
+ config_mock = mock.Mock()
+ config_mock.db_url = f"sqlite:///{tmp_working_dir}/reflex.db"
+ monkeypatch.setattr(reflex.model, "get_config", mock.Mock(return_value=config_mock))
+
+ assert alembic_ini.exists() is False
+ assert versions.exists() is False
+ Model.alembic_init()
+ assert alembic_ini.exists()
+ assert versions.exists()
+
+ class Base(DeclarativeBase):
+ @declared_attr.directive
+ def __tablename__(cls) -> str:
+ return cls.__name__.lower()
+
+ assert model_registry.register(Base)
+
+ class ModelBase(Base, MappedAsDataclass):
+ __abstract__ = True
+ id: Mapped[Optional[int]] = mapped_column(primary_key=True, default=None)
+
+ # initial table
+ class AlembicThing(ModelBase): # pyright: ignore[reportGeneralTypeIssues]
+ t1: Mapped[str] = mapped_column(default="")
+
+ with Model.get_db_engine().connect() as connection:
+ assert Model.alembic_autogenerate(
+ connection=connection, message="Initial Revision"
+ )
+ assert Model.migrate()
+ version_scripts = list(versions.glob("*.py"))
+ assert len(version_scripts) == 1
+ assert version_scripts[0].name.endswith("initial_revision.py")
+
+ with sqla_session() as session:
+ session.add(AlembicThing(t1="foo"))
+ session.commit()
+
+ model_registry.get_metadata().clear()
+
+ # Create column t2, mark t1 as optional with default
+ class AlembicThing(ModelBase): # pyright: ignore[reportGeneralTypeIssues]
+ t1: Mapped[Optional[str]] = mapped_column(default="default")
+ t2: Mapped[str] = mapped_column(default="bar")
+
+ assert Model.migrate(autogenerate=True)
+ assert len(list(versions.glob("*.py"))) == 2
+
+ with sqla_session() as session:
+ session.add(AlembicThing(t2="baz"))
+ session.commit()
+ result = session.scalars(select(AlembicThing)).all()
+ assert len(result) == 2
+ assert result[0].t1 == "foo"
+ assert result[0].t2 == "bar"
+ assert result[1].t1 == "default"
+ assert result[1].t2 == "baz"
+
+ model_registry.get_metadata().clear()
+
+ # Drop column t1
+ class AlembicThing(ModelBase): # pyright: ignore[reportGeneralTypeIssues]
+ t2: Mapped[str] = mapped_column(default="bar")
+
+ assert Model.migrate(autogenerate=True)
+ assert len(list(versions.glob("*.py"))) == 3
+
+ with sqla_session() as session:
+ result = session.scalars(select(AlembicThing)).all()
+ assert len(result) == 2
+ assert result[0].t2 == "bar"
+ assert result[1].t2 == "baz"
+
+ # Add table
+ class AlembicSecond(ModelBase):
+ a: Mapped[int] = mapped_column(default=42)
+ b: Mapped[float] = mapped_column(default=4.2)
+
+ assert Model.migrate(autogenerate=True)
+ assert len(list(versions.glob("*.py"))) == 4
+
+ with reflex.model.session() as session:
+ session.add(AlembicSecond(id=None))
+ session.commit()
+ result = session.scalars(select(AlembicSecond)).all()
+ assert len(result) == 1
+ assert result[0].a == 42
+ assert result[0].b == 4.2
+
+ # No-op
+ # assert Model.migrate(autogenerate=True)
+ # assert len(list(versions.glob("*.py"))) == 4
+
+ # drop table (AlembicSecond)
+ model_registry.get_metadata().clear()
+
+ class AlembicThing(ModelBase): # pyright: ignore[reportGeneralTypeIssues]
+ t2: Mapped[str] = mapped_column(default="bar")
+
+ assert Model.migrate(autogenerate=True)
+ assert len(list(versions.glob("*.py"))) == 5
+
+ with reflex.model.session() as session:
+ with pytest.raises(OperationalError) as errctx:
+ _ = session.scalars(select(AlembicSecond)).all()
+ assert errctx.match(r"no such table: alembicsecond")
+ # first table should still exist
+ result = session.scalars(select(AlembicThing)).all()
+ assert len(result) == 2
+ assert result[0].t2 == "bar"
+ assert result[1].t2 == "baz"
+
+ model_registry.get_metadata().clear()
+
+ class AlembicThing(ModelBase):
+ # changing column type not supported by default
+ t2: Mapped[int] = mapped_column(default=42)
+
+ assert Model.migrate(autogenerate=True)
+ assert len(list(versions.glob("*.py"))) == 5
+
+ # clear all metadata to avoid influencing subsequent tests
+ model_registry.get_metadata().clear()
+
+ # drop remaining tables
+ assert Model.migrate(autogenerate=True)
+ assert len(list(versions.glob("*.py"))) == 6
diff --git a/tests/test_state.py b/tests/units/test_state.py
similarity index 73%
rename from tests/test_state.py
rename to tests/units/test_state.py
index e6e16ddef..271f2e794 100644
--- a/tests/test_state.py
+++ b/tests/units/test_state.py
@@ -2,20 +2,27 @@ from __future__ import annotations
import asyncio
import copy
+import dataclasses
import datetime
import functools
import json
import os
import sys
-from typing import Any, Dict, Generator, List, Optional, Union
+import threading
+from textwrap import dedent
+from typing import Any, AsyncGenerator, Callable, Dict, List, Optional, Union
from unittest.mock import AsyncMock, Mock
import pytest
+import pytest_asyncio
from plotly.graph_objects import Figure
import reflex as rx
+import reflex.config
+from reflex import constants
from reflex.app import App
from reflex.base import Base
+from reflex.components.sonner.toast import Toaster
from reflex.constants import CompileVars, RouteVar, SocketEvent
from reflex.event import Event, EventHandler
from reflex.state import (
@@ -27,15 +34,19 @@ from reflex.state import (
RouterData,
State,
StateManager,
+ StateManagerDisk,
StateManagerMemory,
StateManagerRedis,
StateProxy,
StateUpdate,
_substate_key,
)
+from reflex.testing import chdir
from reflex.utils import format, prerequisites, types
+from reflex.utils.exceptions import SetUndefinedStateVarError
from reflex.utils.format import json_dumps
-from reflex.vars import BaseVar, ComputedVar
+from reflex.vars.base import ComputedVar, Var
+from tests.units.states.mutation import MutableSQLAModel, MutableTestState
from .states import GenState
@@ -51,6 +62,7 @@ formatted_router = {
"origin": "",
"upgrade": "",
"connection": "",
+ "cookie": "",
"pragma": "",
"cache_control": "",
"user_agent": "",
@@ -94,6 +106,8 @@ class TestState(BaseState):
complex: Dict[int, Object] = {1: Object(), 2: Object()}
fig: Figure = Figure()
dt: datetime.datetime = datetime.datetime.fromisoformat("1989-11-09T18:53:00+01:00")
+ _backend: int = 0
+ asynctest: int = 0
@ComputedVar
def sum(self) -> float:
@@ -117,6 +131,14 @@ class TestState(BaseState):
"""Do something."""
pass
+ async def set_asynctest(self, value: int):
+ """Set the asynctest value. Intentionally overwrite the default setter with an async one.
+
+ Args:
+ value: The new value.
+ """
+ self.asynctest = value
+
class ChildState(TestState):
"""A child state fixture."""
@@ -160,7 +182,7 @@ class GrandchildState(ChildState):
class GrandchildState2(ChildState2):
"""A grandchild state fixture."""
- @rx.cached_var
+ @rx.var(cache=True)
def cached(self) -> str:
"""A cached var.
@@ -212,7 +234,7 @@ def child_state(test_state) -> ChildState:
Returns:
A test child state.
"""
- child_state = test_state.get_substate(["child_state"])
+ child_state = test_state.get_substate([ChildState.get_name()])
assert child_state is not None
return child_state
@@ -227,7 +249,7 @@ def child_state2(test_state) -> ChildState2:
Returns:
A second test child state.
"""
- child_state2 = test_state.get_substate(["child_state2"])
+ child_state2 = test_state.get_substate([ChildState2.get_name()])
assert child_state2 is not None
return child_state2
@@ -242,7 +264,7 @@ def grandchild_state(child_state) -> GrandchildState:
Returns:
A test state.
"""
- grandchild_state = child_state.get_substate(["grandchild_state"])
+ grandchild_state = child_state.get_substate([GrandchildState.get_name()])
assert grandchild_state is not None
return grandchild_state
@@ -260,12 +282,12 @@ def test_base_class_vars(test_state):
if field in test_state.get_skip_vars():
continue
prop = getattr(cls, field)
- assert isinstance(prop, BaseVar)
- assert prop._var_name == field
+ assert isinstance(prop, Var)
+ assert prop._js_expr.split(".")[-1] == field
- assert cls.num1._var_type == int
- assert cls.num2._var_type == float
- assert cls.key._var_type == str
+ assert cls.num1._var_type is int
+ assert cls.num2._var_type is float
+ assert cls.key._var_type is str
def test_computed_class_var(test_state):
@@ -275,7 +297,7 @@ def test_computed_class_var(test_state):
test_state: A state.
"""
cls = type(test_state)
- vars = [(prop._var_name, prop._var_type) for prop in cls.computed_vars.values()]
+ vars = [(prop._js_expr, prop._var_type) for prop in cls.computed_vars.values()]
assert ("sum", float) in vars
assert ("upper", str) in vars
@@ -287,7 +309,7 @@ def test_class_vars(test_state):
test_state: A state.
"""
cls = type(test_state)
- assert set(cls.vars.keys()) == {
+ assert cls.vars.keys() == {
"router",
"num1",
"num2",
@@ -301,6 +323,7 @@ def test_class_vars(test_state):
"upper",
"fig",
"dt",
+ "asynctest",
}
@@ -310,7 +333,7 @@ def test_event_handlers(test_state):
Args:
test_state: A state.
"""
- expected = {
+ expected_keys = (
"do_something",
"set_array",
"set_complex",
@@ -320,10 +343,10 @@ def test_event_handlers(test_state):
"set_num1",
"set_num2",
"set_obj",
- }
+ )
cls = type(test_state)
- assert set(cls.event_handlers.keys()).intersection(expected) == expected
+ assert all(key in cls.event_handlers for key in expected_keys)
def test_default_value(test_state):
@@ -352,20 +375,20 @@ def test_computed_vars(test_state):
assert test_state.upper == "HELLO WORLD"
-def test_dict(test_state):
+def test_dict(test_state: TestState):
"""Test that the dict representation of a state is correct.
Args:
test_state: A state.
"""
substates = {
- "test_state",
- "test_state.child_state",
- "test_state.child_state.grandchild_state",
- "test_state.child_state2",
- "test_state.child_state2.grandchild_state2",
- "test_state.child_state3",
- "test_state.child_state3.grandchild_state3",
+ test_state.get_full_name(),
+ ChildState.get_full_name(),
+ GrandchildState.get_full_name(),
+ ChildState2.get_full_name(),
+ GrandchildState2.get_full_name(),
+ ChildState3.get_full_name(),
+ GrandchildState3.get_full_name(),
}
test_state_dict = test_state.dict()
assert set(test_state_dict) == substates
@@ -389,22 +412,27 @@ def test_default_setters(test_state):
def test_class_indexing_with_vars():
"""Test that we can index into a state var with another var."""
prop = TestState.array[TestState.num1]
- assert str(prop) == "{test_state.array.at(test_state.num1)}"
+ assert str(prop) == f"{TestState.get_name()}.array.at({TestState.get_name()}.num1)"
prop = TestState.mapping["a"][TestState.num1]
- assert str(prop) == '{test_state.mapping["a"].at(test_state.num1)}'
+ assert (
+ str(prop)
+ == f'{TestState.get_name()}.mapping["a"].at({TestState.get_name()}.num1)'
+ )
prop = TestState.mapping[TestState.map_key]
- assert str(prop) == "{test_state.mapping[test_state.map_key]}"
+ assert (
+ str(prop) == f"{TestState.get_name()}.mapping[{TestState.get_name()}.map_key]"
+ )
def test_class_attributes():
"""Test that we can get class attributes."""
prop = TestState.obj.prop1
- assert str(prop) == "{test_state.obj.prop1}"
+ assert str(prop) == f'{TestState.get_name()}.obj["prop1"]'
prop = TestState.complex[1].prop1
- assert str(prop) == "{test_state.complex[1].prop1}"
+ assert str(prop) == f'{TestState.get_name()}.complex[1]["prop1"]'
def test_get_parent_state():
@@ -426,27 +454,42 @@ def test_get_substates():
def test_get_name():
"""Test getting the name of a state."""
- assert TestState.get_name() == "test_state"
- assert ChildState.get_name() == "child_state"
- assert ChildState2.get_name() == "child_state2"
- assert GrandchildState.get_name() == "grandchild_state"
+ assert TestState.get_name() == "tests___units___test_state____test_state"
+ assert ChildState.get_name() == "tests___units___test_state____child_state"
+ assert ChildState2.get_name() == "tests___units___test_state____child_state2"
+ assert (
+ GrandchildState.get_name() == "tests___units___test_state____grandchild_state"
+ )
def test_get_full_name():
"""Test getting the full name."""
- assert TestState.get_full_name() == "test_state"
- assert ChildState.get_full_name() == "test_state.child_state"
- assert ChildState2.get_full_name() == "test_state.child_state2"
- assert GrandchildState.get_full_name() == "test_state.child_state.grandchild_state"
+ assert TestState.get_full_name() == "tests___units___test_state____test_state"
+ assert (
+ ChildState.get_full_name()
+ == "tests___units___test_state____test_state.tests___units___test_state____child_state"
+ )
+ assert (
+ ChildState2.get_full_name()
+ == "tests___units___test_state____test_state.tests___units___test_state____child_state2"
+ )
+ assert (
+ GrandchildState.get_full_name()
+ == "tests___units___test_state____test_state.tests___units___test_state____child_state.tests___units___test_state____grandchild_state"
+ )
def test_get_class_substate():
"""Test getting the substate of a class."""
- assert TestState.get_class_substate(("child_state",)) == ChildState
- assert TestState.get_class_substate(("child_state2",)) == ChildState2
- assert ChildState.get_class_substate(("grandchild_state",)) == GrandchildState
+ assert TestState.get_class_substate((ChildState.get_name(),)) == ChildState
+ assert TestState.get_class_substate((ChildState2.get_name(),)) == ChildState2
assert (
- TestState.get_class_substate(("child_state", "grandchild_state"))
+ ChildState.get_class_substate((GrandchildState.get_name(),)) == GrandchildState
+ )
+ assert (
+ TestState.get_class_substate(
+ (ChildState.get_name(), GrandchildState.get_name())
+ )
== GrandchildState
)
with pytest.raises(ValueError):
@@ -454,7 +497,7 @@ def test_get_class_substate():
with pytest.raises(ValueError):
TestState.get_class_substate(
(
- "child_state",
+ ChildState.get_name(),
"invalid_child",
)
)
@@ -466,13 +509,15 @@ def test_get_class_var():
assert TestState.get_class_var(("num2",)).equals(TestState.num2)
assert ChildState.get_class_var(("value",)).equals(ChildState.value)
assert GrandchildState.get_class_var(("value2",)).equals(GrandchildState.value2)
- assert TestState.get_class_var(("child_state", "value")).equals(ChildState.value)
+ assert TestState.get_class_var((ChildState.get_name(), "value")).equals(
+ ChildState.value
+ )
assert TestState.get_class_var(
- ("child_state", "grandchild_state", "value2")
+ (ChildState.get_name(), GrandchildState.get_name(), "value2")
).equals(
GrandchildState.value2,
)
- assert ChildState.get_class_var(("grandchild_state", "value2")).equals(
+ assert ChildState.get_class_var((GrandchildState.get_name(), "value2")).equals(
GrandchildState.value2,
)
with pytest.raises(ValueError):
@@ -480,7 +525,7 @@ def test_get_class_var():
with pytest.raises(ValueError):
TestState.get_class_var(
(
- "child_state",
+ ChildState.get_name(),
"invalid_var",
)
)
@@ -490,12 +535,10 @@ def test_set_class_var():
"""Test setting the var of a class."""
with pytest.raises(AttributeError):
TestState.num3 # type: ignore
- TestState._set_var(
- BaseVar(_var_name="num3", _var_type=int)._var_set_state(TestState)
- )
+ TestState._set_var(Var(_js_expr="num3", _var_type=int)._var_set_state(TestState))
var = TestState.num3 # type: ignore
- assert var._var_name == "num3"
- assert var._var_type == int
+ assert var._js_expr == TestState.get_full_name() + ".num3"
+ assert var._var_type is int
assert var._var_state == TestState.get_full_name()
@@ -508,11 +551,15 @@ def test_set_parent_and_substates(test_state, child_state, grandchild_state):
grandchild_state: A grandchild state.
"""
assert len(test_state.substates) == 3
- assert set(test_state.substates) == {"child_state", "child_state2", "child_state3"}
+ assert set(test_state.substates) == {
+ ChildState.get_name(),
+ ChildState2.get_name(),
+ ChildState3.get_name(),
+ }
assert child_state.parent_state == test_state
assert len(child_state.substates) == 1
- assert set(child_state.substates) == {"grandchild_state"}
+ assert set(child_state.substates) == {GrandchildState.get_name()}
assert grandchild_state.parent_state == child_state
assert len(grandchild_state.substates) == 0
@@ -579,18 +626,21 @@ def test_get_substate(test_state, child_state, child_state2, grandchild_state):
child_state2: A child state.
grandchild_state: A grandchild state.
"""
- assert test_state.get_substate(("child_state",)) == child_state
- assert test_state.get_substate(("child_state2",)) == child_state2
+ assert test_state.get_substate((ChildState.get_name(),)) == child_state
+ assert test_state.get_substate((ChildState2.get_name(),)) == child_state2
assert (
- test_state.get_substate(("child_state", "grandchild_state")) == grandchild_state
+ test_state.get_substate((ChildState.get_name(), GrandchildState.get_name()))
+ == grandchild_state
)
- assert child_state.get_substate(("grandchild_state",)) == grandchild_state
+ assert child_state.get_substate((GrandchildState.get_name(),)) == grandchild_state
with pytest.raises(ValueError):
test_state.get_substate(("invalid",))
with pytest.raises(ValueError):
- test_state.get_substate(("child_state", "invalid"))
+ test_state.get_substate((ChildState.get_name(), "invalid"))
with pytest.raises(ValueError):
- test_state.get_substate(("child_state", "grandchild_state", "invalid"))
+ test_state.get_substate(
+ (ChildState.get_name(), GrandchildState.get_name(), "invalid")
+ )
def test_set_dirty_var(test_state):
@@ -615,7 +665,12 @@ def test_set_dirty_var(test_state):
assert test_state.dirty_vars == set()
-def test_set_dirty_substate(test_state, child_state, child_state2, grandchild_state):
+def test_set_dirty_substate(
+ test_state: TestState,
+ child_state: ChildState,
+ child_state2: ChildState2,
+ grandchild_state: GrandchildState,
+):
"""Test changing substate vars marks the value as dirty.
Args:
@@ -633,7 +688,7 @@ def test_set_dirty_substate(test_state, child_state, child_state2, grandchild_st
# Setting a var should mark it as dirty.
child_state.value = "test"
assert child_state.dirty_vars == {"value"}
- assert test_state.dirty_substates == {"child_state"}
+ assert test_state.dirty_substates == {ChildState.get_name()}
assert child_state.dirty_substates == set()
# Cleaning the parent state should remove the dirty substate.
@@ -643,12 +698,12 @@ def test_set_dirty_substate(test_state, child_state, child_state2, grandchild_st
# Setting a var on the grandchild should bubble up.
grandchild_state.value2 = "test2"
- assert child_state.dirty_substates == {"grandchild_state"}
- assert test_state.dirty_substates == {"child_state"}
+ assert child_state.dirty_substates == {GrandchildState.get_name()}
+ assert test_state.dirty_substates == {ChildState.get_name()}
# Cleaning the middle state should keep the parent state dirty.
child_state._clean()
- assert test_state.dirty_substates == {"child_state"}
+ assert test_state.dirty_substates == {ChildState.get_name()}
assert child_state.dirty_substates == set()
assert grandchild_state.dirty_vars == set()
@@ -663,6 +718,7 @@ def test_reset(test_state, child_state):
# Set some values.
test_state.num1 = 1
test_state.num2 = 2
+ test_state._backend = 3
child_state.value = "test"
# Reset the state.
@@ -671,6 +727,7 @@ def test_reset(test_state, child_state):
# The values should be reset.
assert test_state.num1 == 0
assert test_state.num2 == 3.14
+ assert test_state._backend == 0
assert child_state.value == ""
expected_dirty_vars = {
@@ -686,6 +743,8 @@ def test_reset(test_state, child_state):
"map_key",
"mapping",
"dt",
+ "_backend",
+ "asynctest",
}
# The dirty vars should be reset.
@@ -693,7 +752,11 @@ def test_reset(test_state, child_state):
assert child_state.dirty_vars == {"count", "value"}
# The dirty substates should be reset.
- assert test_state.dirty_substates == {"child_state", "child_state2", "child_state3"}
+ assert test_state.dirty_substates == {
+ ChildState.get_name(),
+ ChildState2.get_name(),
+ ChildState3.get_name(),
+ }
@pytest.mark.asyncio
@@ -714,8 +777,8 @@ async def test_process_event_simple(test_state):
# The delta should contain the changes, including computed vars.
# assert update.delta == {"test_state": {"num1": 69, "sum": 72.14}}
assert update.delta == {
- "test_state": {"num1": 69, "sum": 72.14, "upper": ""},
- "test_state.child_state3.grandchild_state3": {"computed": ""},
+ TestState.get_full_name(): {"num1": 69, "sum": 72.14, "upper": ""},
+ GrandchildState3.get_full_name(): {"computed": ""},
}
assert update.events == []
@@ -733,15 +796,17 @@ async def test_process_event_substate(test_state, child_state, grandchild_state)
assert child_state.value == ""
assert child_state.count == 23
event = Event(
- token="t", name="child_state.change_both", payload={"value": "hi", "count": 12}
+ token="t",
+ name=f"{ChildState.get_name()}.change_both",
+ payload={"value": "hi", "count": 12},
)
update = await test_state._process(event).__anext__()
assert child_state.value == "HI"
assert child_state.count == 24
assert update.delta == {
- "test_state": {"sum": 3.14, "upper": ""},
- "test_state.child_state": {"value": "HI", "count": 24},
- "test_state.child_state3.grandchild_state3": {"computed": ""},
+ TestState.get_full_name(): {"sum": 3.14, "upper": ""},
+ ChildState.get_full_name(): {"value": "HI", "count": 24},
+ GrandchildState3.get_full_name(): {"computed": ""},
}
test_state._clean()
@@ -749,15 +814,15 @@ async def test_process_event_substate(test_state, child_state, grandchild_state)
assert grandchild_state.value2 == ""
event = Event(
token="t",
- name="child_state.grandchild_state.set_value2",
+ name=f"{GrandchildState.get_full_name()}.set_value2",
payload={"value": "new"},
)
update = await test_state._process(event).__anext__()
assert grandchild_state.value2 == "new"
assert update.delta == {
- "test_state": {"sum": 3.14, "upper": ""},
- "test_state.child_state.grandchild_state": {"value2": "new"},
- "test_state.child_state3.grandchild_state3": {"computed": ""},
+ TestState.get_full_name(): {"sum": 3.14, "upper": ""},
+ GrandchildState.get_full_name(): {"value2": "new"},
+ GrandchildState3.get_full_name(): {"computed": ""},
}
@@ -781,7 +846,7 @@ async def test_process_event_generator():
else:
assert gen_state.value == count
assert update.delta == {
- "gen_state": {"value": count},
+ GenState.get_full_name(): {"value": count},
}
assert not update.final
@@ -820,8 +885,10 @@ def test_get_headers(test_state, router_data, router_data_headers):
router_data: The router data fixture.
router_data_headers: The expected headers.
"""
+ print(router_data_headers)
test_state.router = RouterData(router_data)
- assert test_state.router.headers.dict() == {
+ print(test_state.router.headers)
+ assert dataclasses.asdict(test_state.router.headers) == {
format.to_snake_case(k): v for k, v in router_data_headers.items()
}
@@ -903,7 +970,7 @@ class InterdependentState(BaseState):
v1: int = 0
_v2: int = 1
- @rx.cached_var
+ @rx.var(cache=True)
def v1x2(self) -> int:
"""Depends on var v1.
@@ -912,7 +979,7 @@ class InterdependentState(BaseState):
"""
return self.v1 * 2
- @rx.cached_var
+ @rx.var(cache=True)
def v2x2(self) -> int:
"""Depends on backend var _v2.
@@ -921,7 +988,16 @@ class InterdependentState(BaseState):
"""
return self._v2 * 2
- @rx.cached_var
+ @rx.var(cache=True, backend=True)
+ def v2x2_backend(self) -> int:
+ """Depends on backend var _v2.
+
+ Returns:
+ backend var _v2 multiplied by 2
+ """
+ return self._v2 * 2
+
+ @rx.var(cache=True)
def v1x2x2(self) -> int:
"""Depends on ComputedVar v1x2.
@@ -930,7 +1006,7 @@ class InterdependentState(BaseState):
"""
return self.v1x2 * 2 # type: ignore
- @rx.cached_var
+ @rx.var(cache=True)
def _v3(self) -> int:
"""Depends on backend var _v2.
@@ -939,7 +1015,7 @@ class InterdependentState(BaseState):
"""
return self._v2
- @rx.cached_var
+ @rx.var(cache=True)
def v3x2(self) -> int:
"""Depends on ComputedVar _v3.
@@ -961,7 +1037,24 @@ def interdependent_state() -> BaseState:
return s
-def test_not_dirty_computed_var_from_var(interdependent_state):
+def test_interdependent_state_initial_dict() -> None:
+ s = InterdependentState()
+ state_name = s.get_name()
+ d = s.dict(initial=True)[state_name]
+ d.pop("router")
+ assert d == {
+ "x": 0,
+ "v1": 0,
+ "v1x2": 0,
+ "v2x2": 2,
+ "v1x2x2": 0,
+ "v3x2": 2,
+ }
+
+
+def test_not_dirty_computed_var_from_var(
+ interdependent_state: InterdependentState,
+) -> None:
"""Set Var that no ComputedVar depends on, expect no recalculation.
Args:
@@ -973,7 +1066,7 @@ def test_not_dirty_computed_var_from_var(interdependent_state):
}
-def test_dirty_computed_var_from_var(interdependent_state):
+def test_dirty_computed_var_from_var(interdependent_state: InterdependentState) -> None:
"""Set Var that ComputedVar depends on, expect recalculation.
The other ComputedVar depends on the changed ComputedVar and should also be
@@ -988,20 +1081,23 @@ def test_dirty_computed_var_from_var(interdependent_state):
}
-def test_dirty_computed_var_from_backend_var(interdependent_state):
+def test_dirty_computed_var_from_backend_var(
+ interdependent_state: InterdependentState,
+) -> None:
"""Set backend var that ComputedVar depends on, expect recalculation.
Args:
interdependent_state: A state with varying Var dependencies.
"""
+ # Accessing ._v3 returns the immutable var it represents instead of the actual computed var
+ # assert InterdependentState._v3._backend is True
interdependent_state._v2 = 2
assert interdependent_state.get_delta() == {
interdependent_state.get_full_name(): {"v2x2": 4, "v3x2": 4},
}
- assert "_v3" in InterdependentState.backend_vars
-def test_per_state_backend_var(interdependent_state):
+def test_per_state_backend_var(interdependent_state: InterdependentState) -> None:
"""Set backend var on one instance, expect no affect in other instances.
Args:
@@ -1124,7 +1220,7 @@ def test_computed_var_cached():
class ComputedState(BaseState):
v: int = 0
- @rx.cached_var
+ @rx.var(cache=True)
def comp_v(self) -> int:
nonlocal comp_v_calls
comp_v_calls += 1
@@ -1144,7 +1240,7 @@ def test_computed_var_cached():
def test_computed_var_cached_depends_on_non_cached():
- """Test that a cached_var is recalculated if it depends on non-cached ComputedVar."""
+ """Test that a cached var is recalculated if it depends on non-cached ComputedVar."""
class ComputedState(BaseState):
v: int = 0
@@ -1153,11 +1249,11 @@ def test_computed_var_cached_depends_on_non_cached():
def no_cache_v(self) -> int:
return self.v
- @rx.cached_var
+ @rx.var(cache=True)
def dep_v(self) -> int:
return self.no_cache_v # type: ignore
- @rx.cached_var
+ @rx.var(cache=True)
def comp_v(self) -> int:
return self.v
@@ -1185,7 +1281,7 @@ def test_computed_var_cached_depends_on_non_cached():
def test_computed_var_depends_on_parent_non_cached():
- """Child state cached_var that depends on parent state un cached var is always recalculated."""
+ """Child state cached var that depends on parent state un cached var is always recalculated."""
counter = 0
class ParentState(BaseState):
@@ -1196,7 +1292,7 @@ def test_computed_var_depends_on_parent_non_cached():
return counter
class ChildState(ParentState):
- @rx.cached_var
+ @rx.var(cache=True)
def dep_v(self) -> int:
return self.no_cache_v # type: ignore
@@ -1206,19 +1302,19 @@ def test_computed_var_depends_on_parent_non_cached():
assert ps.dirty_vars == set()
assert cs.dirty_vars == set()
- dict1 = ps.dict()
+ dict1 = json.loads(json_dumps(ps.dict()))
assert dict1[ps.get_full_name()] == {
"no_cache_v": 1,
"router": formatted_router,
}
assert dict1[cs.get_full_name()] == {"dep_v": 2}
- dict2 = ps.dict()
+ dict2 = json.loads(json_dumps(ps.dict()))
assert dict2[ps.get_full_name()] == {
"no_cache_v": 3,
"router": formatted_router,
}
assert dict2[cs.get_full_name()] == {"dep_v": 4}
- dict3 = ps.dict()
+ dict3 = json.loads(json_dumps(ps.dict()))
assert dict3[ps.get_full_name()] == {
"no_cache_v": 5,
"router": formatted_router,
@@ -1229,7 +1325,7 @@ def test_computed_var_depends_on_parent_non_cached():
@pytest.mark.parametrize("use_partial", [True, False])
def test_cached_var_depends_on_event_handler(use_partial: bool):
- """A cached_var that calls an event handler calculates deps correctly.
+ """A cached var that calls an event handler calculates deps correctly.
Args:
use_partial: if true, replace the EventHandler with functools.partial
@@ -1242,7 +1338,7 @@ def test_cached_var_depends_on_event_handler(use_partial: bool):
def handler(self):
self.x = self.x + 1
- @rx.cached_var
+ @rx.var(cache=True)
def cached_x_side_effect(self) -> int:
self.handler()
nonlocal counter
@@ -1274,7 +1370,11 @@ def test_computed_var_dependencies():
y: List[int] = [1, 2, 3]
_z: List[int] = [1, 2, 3]
- @rx.cached_var
+ @property
+ def testprop(self) -> int:
+ return self.v
+
+ @rx.var(cache=True)
def comp_v(self) -> int:
"""Direct access.
@@ -1283,7 +1383,25 @@ def test_computed_var_dependencies():
"""
return self.v
- @rx.cached_var
+ @rx.var(cache=True, backend=True)
+ def comp_v_backend(self) -> int:
+ """Direct access backend var.
+
+ Returns:
+ The value of self.v.
+ """
+ return self.v
+
+ @rx.var(cache=True)
+ def comp_v_via_property(self) -> int:
+ """Access v via property.
+
+ Returns:
+ The value of v via property.
+ """
+ return self.testprop
+
+ @rx.var(cache=True)
def comp_w(self):
"""Nested lambda.
@@ -1292,7 +1410,7 @@ def test_computed_var_dependencies():
"""
return lambda: self.w
- @rx.cached_var
+ @rx.var(cache=True)
def comp_x(self):
"""Nested function.
@@ -1305,7 +1423,7 @@ def test_computed_var_dependencies():
return _
- @rx.cached_var
+ @rx.var(cache=True)
def comp_y(self) -> List[int]:
"""Comprehension iterating over attribute.
@@ -1314,7 +1432,7 @@ def test_computed_var_dependencies():
"""
return [round(y) for y in self.y]
- @rx.cached_var
+ @rx.var(cache=True)
def comp_z(self) -> List[bool]:
"""Comprehension accesses attribute.
@@ -1324,7 +1442,11 @@ def test_computed_var_dependencies():
return [z in self._z for z in range(5)]
cs = ComputedState()
- assert cs._computed_var_dependencies["v"] == {"comp_v"}
+ assert cs._computed_var_dependencies["v"] == {
+ "comp_v",
+ "comp_v_backend",
+ "comp_v_via_property",
+ }
assert cs._computed_var_dependencies["w"] == {"comp_w"}
assert cs._computed_var_dependencies["x"] == {"comp_x"}
assert cs._computed_var_dependencies["y"] == {"comp_y"}
@@ -1346,7 +1468,7 @@ def test_backend_method():
assert bms._be_method()
-def test_setattr_of_mutable_types(mutable_state):
+def test_setattr_of_mutable_types(mutable_state: MutableTestState):
"""Test that mutable types are converted to corresponding Reflex wrappers.
Args:
@@ -1355,6 +1477,7 @@ def test_setattr_of_mutable_types(mutable_state):
array = mutable_state.array
hashmap = mutable_state.hashmap
test_set = mutable_state.test_set
+ sqla_model = mutable_state.sqla_model
assert isinstance(array, MutableProxy)
assert isinstance(array, list)
@@ -1382,11 +1505,21 @@ def test_setattr_of_mutable_types(mutable_state):
assert isinstance(mutable_state.custom.test_set, set)
assert isinstance(mutable_state.custom.custom, MutableProxy)
+ assert isinstance(sqla_model, MutableProxy)
+ assert isinstance(sqla_model, MutableSQLAModel)
+ assert isinstance(sqla_model.strlist, MutableProxy)
+ assert isinstance(sqla_model.strlist, list)
+ assert isinstance(sqla_model.hashmap, MutableProxy)
+ assert isinstance(sqla_model.hashmap, dict)
+ assert isinstance(sqla_model.test_set, MutableProxy)
+ assert isinstance(sqla_model.test_set, set)
+
mutable_state.reassign_mutables()
array = mutable_state.array
hashmap = mutable_state.hashmap
test_set = mutable_state.test_set
+ sqla_model = mutable_state.sqla_model
assert isinstance(array, MutableProxy)
assert isinstance(array, list)
@@ -1405,6 +1538,15 @@ def test_setattr_of_mutable_types(mutable_state):
assert isinstance(test_set, MutableProxy)
assert isinstance(test_set, set)
+ assert isinstance(sqla_model, MutableProxy)
+ assert isinstance(sqla_model, MutableSQLAModel)
+ assert isinstance(sqla_model.strlist, MutableProxy)
+ assert isinstance(sqla_model.strlist, list)
+ assert isinstance(sqla_model.hashmap, MutableProxy)
+ assert isinstance(sqla_model.hashmap, dict)
+ assert isinstance(sqla_model.test_set, MutableProxy)
+ assert isinstance(sqla_model.test_set, set)
+
def test_error_on_state_method_shadow():
"""Test that an error is thrown when an event handler shadows a state method."""
@@ -1421,11 +1563,12 @@ def test_error_on_state_method_shadow():
@pytest.mark.asyncio
-async def test_state_with_invalid_yield(capsys):
+async def test_state_with_invalid_yield(capsys, mock_app):
"""Test that an error is thrown when a state yields an invalid value.
Args:
capsys: Pytest fixture for capture standard streams.
+ mock_app: Mock app fixture.
"""
class StateWithInvalidYield(BaseState):
@@ -1444,16 +1587,37 @@ async def test_state_with_invalid_yield(capsys):
rx.event.Event(token="fake_token", name="invalid_handler")
):
assert not update.delta
- assert update.events == rx.event.fix_events(
- [rx.window_alert("An error occurred. See logs for details.")],
- token="",
- )
+ if Toaster.is_used:
+ assert update.events == rx.event.fix_events(
+ [
+ rx.toast(
+ "An error occurred.",
+ description="TypeError: Your handler test_state_with_invalid_yield..StateWithInvalidYield.invalid_handler must only return/yield: None, Events or other EventHandlers referenced by their class (not using `self`). See logs for details.",
+ level="error",
+ id="backend_error",
+ position="top-center",
+ style={"width": "500px"},
+ ) # type: ignore
+ ],
+ token="",
+ )
+ else:
+ assert update.events == rx.event.fix_events(
+ [
+ rx.window_alert(
+ "An error occurred.\nContact the website administrator."
+ )
+ ],
+ token="",
+ )
captured = capsys.readouterr()
assert "must only return/yield: None, Events or other EventHandlers" in captured.out
-@pytest.fixture(scope="function", params=["in_process", "redis"])
-def state_manager(request) -> Generator[StateManager, None, None]:
+@pytest_asyncio.fixture(
+ loop_scope="function", scope="function", params=["in_process", "disk", "redis"]
+)
+async def state_manager(request) -> AsyncGenerator[StateManager, None]:
"""Instance of state manager parametrized for redis and in-process.
Args:
@@ -1466,15 +1630,18 @@ def state_manager(request) -> Generator[StateManager, None, None]:
if request.param == "redis":
if not isinstance(state_manager, StateManagerRedis):
pytest.skip("Test requires redis")
- else:
+ elif request.param == "disk":
# explicitly NOT using redis
+ state_manager = StateManagerDisk(state=TestState)
+ assert not state_manager._states_locks
+ else:
state_manager = StateManagerMemory(state=TestState)
assert not state_manager._states_locks
yield state_manager
if isinstance(state_manager, StateManagerRedis):
- asyncio.get_event_loop().run_until_complete(state_manager.close())
+ await state_manager.close()
@pytest.fixture()
@@ -1505,7 +1672,7 @@ async def test_state_manager_modify_state(
async with state_manager.modify_state(substate_token) as state:
if isinstance(state_manager, StateManagerRedis):
assert await state_manager.redis.get(f"{token}_lock")
- elif isinstance(state_manager, StateManagerMemory):
+ elif isinstance(state_manager, (StateManagerMemory, StateManagerDisk)):
assert token in state_manager._states_locks
assert state_manager._states_locks[token].locked()
# Should be able to write proxy objects inside mutables
@@ -1515,11 +1682,11 @@ async def test_state_manager_modify_state(
# lock should be dropped after exiting the context
if isinstance(state_manager, StateManagerRedis):
assert (await state_manager.redis.get(f"{token}_lock")) is None
- elif isinstance(state_manager, StateManagerMemory):
+ elif isinstance(state_manager, (StateManagerMemory, StateManagerDisk)):
assert not state_manager._states_locks[token].locked()
# separate instances should NOT share locks
- sm2 = StateManagerMemory(state=TestState)
+ sm2 = state_manager.__class__(state=TestState)
assert sm2._state_manager_lock is state_manager._state_manager_lock
assert not sm2._states_locks
if state_manager._states_locks:
@@ -1557,13 +1724,13 @@ async def test_state_manager_contend(
if isinstance(state_manager, StateManagerRedis):
assert (await state_manager.redis.get(f"{token}_lock")) is None
- elif isinstance(state_manager, StateManagerMemory):
+ elif isinstance(state_manager, (StateManagerMemory, StateManagerDisk)):
assert token in state_manager._states_locks
assert not state_manager._states_locks[token].locked()
-@pytest.fixture(scope="function")
-def state_manager_redis() -> Generator[StateManager, None, None]:
+@pytest_asyncio.fixture(loop_scope="function", scope="function")
+async def state_manager_redis() -> AsyncGenerator[StateManager, None]:
"""Instance of state manager for redis only.
Yields:
@@ -1576,7 +1743,7 @@ def state_manager_redis() -> Generator[StateManager, None, None]:
yield state_manager
- asyncio.get_event_loop().run_until_complete(state_manager.close())
+ await state_manager.close()
@pytest.fixture()
@@ -1697,14 +1864,14 @@ async def test_state_proxy(grandchild_state: GrandchildState, mock_app: rx.App):
assert child_state is not None
parent_state = child_state.parent_state
assert parent_state is not None
- if isinstance(mock_app.state_manager, StateManagerMemory):
- mock_app.state_manager.states[
- parent_state.router.session.client_token
- ] = parent_state
+ if isinstance(mock_app.state_manager, (StateManagerMemory, StateManagerDisk)):
+ mock_app.state_manager.states[parent_state.router.session.client_token] = (
+ parent_state
+ )
sp = StateProxy(grandchild_state)
assert sp.__wrapped__ == grandchild_state
- assert sp._self_substate_path == grandchild_state.get_full_name().split(".")
+ assert sp._self_substate_path == tuple(grandchild_state.get_full_name().split("."))
assert sp._self_app is mock_app
assert not sp._self_mutable
assert sp._self_actx is None
@@ -1736,7 +1903,7 @@ async def test_state_proxy(grandchild_state: GrandchildState, mock_app: rx.App):
async with sp:
assert sp._self_actx is not None
assert sp._self_mutable # proxy is mutable inside context
- if isinstance(mock_app.state_manager, StateManagerMemory):
+ if isinstance(mock_app.state_manager, (StateManagerMemory, StateManagerDisk)):
# For in-process store, only one instance of the state exists
assert sp.__wrapped__ is grandchild_state
else:
@@ -1751,7 +1918,7 @@ async def test_state_proxy(grandchild_state: GrandchildState, mock_app: rx.App):
gotten_state = await mock_app.state_manager.get_state(
_substate_key(grandchild_state.router.session.client_token, grandchild_state)
)
- if isinstance(mock_app.state_manager, StateManagerMemory):
+ if isinstance(mock_app.state_manager, (StateManagerMemory, StateManagerDisk)):
# For in-process store, only one instance of the state exists
assert gotten_state is parent_state
else:
@@ -1765,19 +1932,21 @@ async def test_state_proxy(grandchild_state: GrandchildState, mock_app: rx.App):
mock_app.event_namespace.emit.assert_called_once()
mcall = mock_app.event_namespace.emit.mock_calls[0]
assert mcall.args[0] == str(SocketEvent.EVENT)
- assert json.loads(mcall.args[1]) == StateUpdate(
- delta={
- parent_state.get_full_name(): {
- "upper": "",
- "sum": 3.14,
- },
- grandchild_state.get_full_name(): {
- "value2": "42",
- },
- GrandchildState3.get_full_name(): {
- "computed": "",
- },
- }
+ assert json.loads(mcall.args[1]) == dataclasses.asdict(
+ StateUpdate(
+ delta={
+ parent_state.get_full_name(): {
+ "upper": "",
+ "sum": 3.14,
+ },
+ grandchild_state.get_full_name(): {
+ "value2": "42",
+ },
+ GrandchildState3.get_full_name(): {
+ "computed": "",
+ },
+ }
+ )
)
assert mcall.kwargs["to"] == grandchild_state.router.session.session_id
@@ -1797,7 +1966,7 @@ class BackgroundTaskState(BaseState):
"""
return self.order
- @rx.background
+ @rx.event(background=True)
async def background_task(self):
"""A background task that updates the state."""
async with self:
@@ -1834,7 +2003,7 @@ class BackgroundTaskState(BaseState):
self.other() # direct calling event handlers works in context
self._private_method()
- @rx.background
+ @rx.event(background=True)
async def background_task_reset(self):
"""A background task that resets the state."""
with pytest.raises(ImmutableStateError):
@@ -1848,7 +2017,7 @@ class BackgroundTaskState(BaseState):
async with self:
self.order.append("reset")
- @rx.background
+ @rx.event(background=True)
async def background_task_generator(self):
"""A background task generator that does nothing.
@@ -1889,7 +2058,7 @@ async def test_background_task_no_block(mock_app: rx.App, token: str):
mock_app,
Event(
token=token,
- name=f"{BackgroundTaskState.get_name()}.background_task",
+ name=f"{BackgroundTaskState.get_full_name()}.background_task",
router_data=router_data,
payload={},
),
@@ -1909,7 +2078,7 @@ async def test_background_task_no_block(mock_app: rx.App, token: str):
mock_app,
Event(
token=token,
- name=f"{BackgroundTaskState.get_name()}.other",
+ name=f"{BackgroundTaskState.get_full_name()}.other",
router_data=router_data,
payload={},
),
@@ -1920,7 +2089,7 @@ async def test_background_task_no_block(mock_app: rx.App, token: str):
# other task returns delta
assert update == StateUpdate(
delta={
- BackgroundTaskState.get_name(): {
+ BackgroundTaskState.get_full_name(): {
"order": [
"background_task:start",
"other",
@@ -1956,10 +2125,13 @@ async def test_background_task_no_block(mock_app: rx.App, token: str):
emit_mock = mock_app.event_namespace.emit
first_ws_message = json.loads(emit_mock.mock_calls[0].args[1])
- assert first_ws_message["delta"]["background_task_state"].pop("router") is not None
+ assert (
+ first_ws_message["delta"][BackgroundTaskState.get_full_name()].pop("router")
+ is not None
+ )
assert first_ws_message == {
"delta": {
- "background_task_state": {
+ BackgroundTaskState.get_full_name(): {
"order": ["background_task:start"],
"computed_order": ["background_task:start"],
}
@@ -1970,14 +2142,16 @@ async def test_background_task_no_block(mock_app: rx.App, token: str):
for call in emit_mock.mock_calls[1:5]:
assert json.loads(call.args[1]) == {
"delta": {
- "background_task_state": {"computed_order": ["background_task:start"]}
+ BackgroundTaskState.get_full_name(): {
+ "computed_order": ["background_task:start"],
+ }
},
"events": [],
"final": True,
}
assert json.loads(emit_mock.mock_calls[-2].args[1]) == {
"delta": {
- "background_task_state": {
+ BackgroundTaskState.get_full_name(): {
"order": exp_order,
"computed_order": exp_order,
"dict_list": {},
@@ -1988,7 +2162,7 @@ async def test_background_task_no_block(mock_app: rx.App, token: str):
}
assert json.loads(emit_mock.mock_calls[-1].args[1]) == {
"delta": {
- "background_task_state": {
+ BackgroundTaskState.get_full_name(): {
"computed_order": exp_order,
},
},
@@ -2046,7 +2220,7 @@ async def test_background_task_no_chain():
await bts.bad_chain2()
-def test_mutable_list(mutable_state):
+def test_mutable_list(mutable_state: MutableTestState):
"""Test that mutable lists are tracked correctly.
Args:
@@ -2076,7 +2250,7 @@ def test_mutable_list(mutable_state):
assert_array_dirty()
mutable_state.array.reverse()
assert_array_dirty()
- mutable_state.array.sort()
+ mutable_state.array.sort() # type: ignore[reportCallIssue,reportUnknownMemberType]
assert_array_dirty()
mutable_state.array[0] = 666
assert_array_dirty()
@@ -2100,7 +2274,7 @@ def test_mutable_list(mutable_state):
assert_array_dirty()
-def test_mutable_dict(mutable_state):
+def test_mutable_dict(mutable_state: MutableTestState):
"""Test that mutable dicts are tracked correctly.
Args:
@@ -2114,40 +2288,40 @@ def test_mutable_dict(mutable_state):
assert not mutable_state.dirty_vars
# Test all dict operations
- mutable_state.hashmap.update({"new_key": 43})
+ mutable_state.hashmap.update({"new_key": "43"})
assert_hashmap_dirty()
- assert mutable_state.hashmap.setdefault("another_key", 66) == "another_value"
+ assert mutable_state.hashmap.setdefault("another_key", "66") == "another_value"
assert_hashmap_dirty()
- assert mutable_state.hashmap.setdefault("setdefault_key", 67) == 67
+ assert mutable_state.hashmap.setdefault("setdefault_key", "67") == "67"
assert_hashmap_dirty()
- assert mutable_state.hashmap.setdefault("setdefault_key", 68) == 67
+ assert mutable_state.hashmap.setdefault("setdefault_key", "68") == "67"
assert_hashmap_dirty()
- assert mutable_state.hashmap.pop("new_key") == 43
+ assert mutable_state.hashmap.pop("new_key") == "43"
assert_hashmap_dirty()
mutable_state.hashmap.popitem()
assert_hashmap_dirty()
mutable_state.hashmap.clear()
assert_hashmap_dirty()
- mutable_state.hashmap["new_key"] = 42
+ mutable_state.hashmap["new_key"] = "42"
assert_hashmap_dirty()
del mutable_state.hashmap["new_key"]
assert_hashmap_dirty()
if sys.version_info >= (3, 9):
- mutable_state.hashmap |= {"new_key": 44}
+ mutable_state.hashmap |= {"new_key": "44"}
assert_hashmap_dirty()
# Test nested dict operations
mutable_state.hashmap["array"] = []
assert_hashmap_dirty()
- mutable_state.hashmap["array"].append(1)
+ mutable_state.hashmap["array"].append("1")
assert_hashmap_dirty()
mutable_state.hashmap["dict"] = {}
assert_hashmap_dirty()
- mutable_state.hashmap["dict"]["key"] = 42
+ mutable_state.hashmap["dict"]["key"] = "42"
assert_hashmap_dirty()
mutable_state.hashmap["dict"]["dict"] = {}
assert_hashmap_dirty()
- mutable_state.hashmap["dict"]["dict"]["key"] = 43
+ mutable_state.hashmap["dict"]["dict"]["key"] = "43"
assert_hashmap_dirty()
# Test proxy returned from `setdefault` and `get`
@@ -2169,14 +2343,14 @@ def test_mutable_dict(mutable_state):
mutable_value_third_ref = mutable_state.hashmap.pop("setdefault_mutable_key")
assert not isinstance(mutable_value_third_ref, MutableProxy)
assert_hashmap_dirty()
- mutable_value_third_ref.append("baz")
+ mutable_value_third_ref.append("baz") # type: ignore[reportUnknownMemberType,reportAttributeAccessIssue,reportUnusedCallResult]
assert not mutable_state.dirty_vars
# Unfortunately previous refs still will mark the state dirty... nothing doing about that
assert mutable_value.pop()
assert_hashmap_dirty()
-def test_mutable_set(mutable_state):
+def test_mutable_set(mutable_state: MutableTestState):
"""Test that mutable sets are tracked correctly.
Args:
@@ -2218,7 +2392,7 @@ def test_mutable_set(mutable_state):
assert_set_dirty()
-def test_mutable_custom(mutable_state):
+def test_mutable_custom(mutable_state: MutableTestState):
"""Test that mutable custom types derived from Base are tracked correctly.
Args:
@@ -2233,17 +2407,38 @@ def test_mutable_custom(mutable_state):
mutable_state.custom.foo = "bar"
assert_custom_dirty()
- mutable_state.custom.array.append(42)
+ mutable_state.custom.array.append("42")
assert_custom_dirty()
- mutable_state.custom.hashmap["key"] = 68
+ mutable_state.custom.hashmap["key"] = "value"
assert_custom_dirty()
- mutable_state.custom.test_set.add(42)
+ mutable_state.custom.test_set.add("foo")
assert_custom_dirty()
mutable_state.custom.custom.bar = "baz"
assert_custom_dirty()
-def test_mutable_backend(mutable_state):
+def test_mutable_sqla_model(mutable_state: MutableTestState):
+ """Test that mutable SQLA models are tracked correctly.
+
+ Args:
+ mutable_state: A test state.
+ """
+ assert not mutable_state.dirty_vars
+
+ def assert_sqla_model_dirty():
+ assert mutable_state.dirty_vars == {"sqla_model"}
+ mutable_state._clean()
+ assert not mutable_state.dirty_vars
+
+ mutable_state.sqla_model.strlist.append("foo")
+ assert_sqla_model_dirty()
+ mutable_state.sqla_model.hashmap["key"] = "value"
+ assert_sqla_model_dirty()
+ mutable_state.sqla_model.test_set.add("bar")
+ assert_sqla_model_dirty()
+
+
+def test_mutable_backend(mutable_state: MutableTestState):
"""Test that mutable backend vars are tracked correctly.
Args:
@@ -2258,11 +2453,11 @@ def test_mutable_backend(mutable_state):
mutable_state._be_custom.foo = "bar"
assert_custom_dirty()
- mutable_state._be_custom.array.append(42)
+ mutable_state._be_custom.array.append("baz")
assert_custom_dirty()
- mutable_state._be_custom.hashmap["key"] = 68
+ mutable_state._be_custom.hashmap["key"] = "value"
assert_custom_dirty()
- mutable_state._be_custom.test_set.add(42)
+ mutable_state._be_custom.test_set.add("foo")
assert_custom_dirty()
mutable_state._be_custom.custom.bar = "baz"
assert_custom_dirty()
@@ -2275,7 +2470,7 @@ def test_mutable_backend(mutable_state):
(copy.deepcopy,),
],
)
-def test_mutable_copy(mutable_state, copy_func):
+def test_mutable_copy(mutable_state: MutableTestState, copy_func: Callable):
"""Test that mutable types are copied correctly.
Args:
@@ -2302,7 +2497,7 @@ def test_mutable_copy(mutable_state, copy_func):
(copy.deepcopy,),
],
)
-def test_mutable_copy_vars(mutable_state, copy_func):
+def test_mutable_copy_vars(mutable_state: MutableTestState, copy_func: Callable):
"""Test that mutable types are copied correctly.
Args:
@@ -2319,7 +2514,10 @@ def test_mutable_copy_vars(mutable_state, copy_func):
def test_duplicate_substate_class(mocker):
+ # Neuter pytest escape hatch, because we want to test duplicate detection.
mocker.patch("reflex.state.is_testing_env", lambda: False)
+ # Neuter state handling since these _are_ defined inside a function.
+ mocker.patch("reflex.state.BaseState._handle_local_def", lambda: None)
with pytest.raises(ValueError):
class TestState(BaseState):
@@ -2347,7 +2545,7 @@ def test_json_dumps_with_mutables():
items: List[Foo] = [Foo()]
dict_val = MutableContainsBase().dict()
- assert isinstance(dict_val[MutableContainsBase.get_full_name()]["items"][0], dict)
+ assert isinstance(dict_val[MutableContainsBase.get_full_name()]["items"][0], Foo)
val = json_dumps(dict_val)
f_items = '[{"tags": ["123", "456"]}]'
f_formatted_router = str(formatted_router).replace("'", '"')
@@ -2392,6 +2590,22 @@ class Custom1(Base):
foo: str
+ def set_foo(self, val: str):
+ """Set the attribute foo.
+
+ Args:
+ val: The value to set.
+ """
+ self.foo = val
+
+ def double_foo(self) -> str:
+ """Concantenate foo with foo.
+
+ Returns:
+ foo + foo
+ """
+ return self.foo + self.foo
+
class Custom2(Base):
"""A custom class with a Custom1 field."""
@@ -2399,6 +2613,14 @@ class Custom2(Base):
c1: Optional[Custom1] = None
c1r: Custom1
+ def set_c1r_foo(self, val: str):
+ """Set the foo attribute of the c1 field.
+
+ Args:
+ val: The value to set.
+ """
+ self.c1r.set_foo(val)
+
class Custom3(Base):
"""A custom class with a Custom2 field."""
@@ -2418,15 +2640,23 @@ def test_state_union_optional():
c3r: Custom3 = Custom3(c2r=Custom2(c1r=Custom1(foo="")))
custom_union: Union[Custom1, Custom2, Custom3] = Custom1(foo="")
- assert UnionState.c3.c2._var_name == "c3?.c2" # type: ignore
- assert UnionState.c3.c2.c1._var_name == "c3?.c2?.c1" # type: ignore
- assert UnionState.c3.c2.c1.foo._var_name == "c3?.c2?.c1?.foo" # type: ignore
- assert UnionState.c3.c2.c1r.foo._var_name == "c3?.c2?.c1r.foo" # type: ignore
- assert UnionState.c3.c2r.c1._var_name == "c3?.c2r.c1" # type: ignore
- assert UnionState.c3.c2r.c1.foo._var_name == "c3?.c2r.c1?.foo" # type: ignore
- assert UnionState.c3.c2r.c1r.foo._var_name == "c3?.c2r.c1r.foo" # type: ignore
- assert UnionState.c3i.c2._var_name == "c3i.c2" # type: ignore
- assert UnionState.c3r.c2._var_name == "c3r.c2" # type: ignore
+ assert str(UnionState.c3.c2) == f'{str(UnionState.c3)}?.["c2"]' # type: ignore
+ assert str(UnionState.c3.c2.c1) == f'{str(UnionState.c3)}?.["c2"]?.["c1"]' # type: ignore
+ assert (
+ str(UnionState.c3.c2.c1.foo) == f'{str(UnionState.c3)}?.["c2"]?.["c1"]?.["foo"]' # type: ignore
+ )
+ assert (
+ str(UnionState.c3.c2.c1r.foo) == f'{str(UnionState.c3)}?.["c2"]?.["c1r"]["foo"]' # type: ignore
+ )
+ assert str(UnionState.c3.c2r.c1) == f'{str(UnionState.c3)}?.["c2r"]["c1"]' # type: ignore
+ assert (
+ str(UnionState.c3.c2r.c1.foo) == f'{str(UnionState.c3)}?.["c2r"]["c1"]?.["foo"]' # type: ignore
+ )
+ assert (
+ str(UnionState.c3.c2r.c1r.foo) == f'{str(UnionState.c3)}?.["c2r"]["c1r"]["foo"]' # type: ignore
+ )
+ assert str(UnionState.c3i.c2) == f'{str(UnionState.c3i)}["c2"]' # type: ignore
+ assert str(UnionState.c3r.c2) == f'{str(UnionState.c3r)}["c2"]' # type: ignore
assert UnionState.custom_union.foo is not None # type: ignore
assert UnionState.custom_union.c1 is not None # type: ignore
assert UnionState.custom_union.c1r is not None # type: ignore
@@ -2436,6 +2666,47 @@ def test_state_union_optional():
assert types.is_union(UnionState.int_float._var_type) # type: ignore
+def test_set_base_field_via_setter():
+ """When calling a setter on a Base instance, also track changes."""
+
+ class BaseFieldSetterState(BaseState):
+ c1: Custom1 = Custom1(foo="")
+ c2: Custom2 = Custom2(c1r=Custom1(foo=""))
+
+ bfss = BaseFieldSetterState()
+ assert "c1" not in bfss.dirty_vars
+
+ # Non-mutating function, not dirty
+ bfss.c1.double_foo()
+ assert "c1" not in bfss.dirty_vars
+
+ # Mutating function, dirty
+ bfss.c1.set_foo("bar")
+ assert "c1" in bfss.dirty_vars
+ bfss.dirty_vars.clear()
+ assert "c1" not in bfss.dirty_vars
+
+ # Mutating function from Base, dirty
+ bfss.c1.set(foo="bar")
+ assert "c1" in bfss.dirty_vars
+ bfss.dirty_vars.clear()
+ assert "c1" not in bfss.dirty_vars
+
+ # Assert identity of MutableProxy
+ mp = bfss.c1
+ assert isinstance(mp, MutableProxy)
+ mp2 = mp.set()
+ assert mp is mp2
+ mp3 = bfss.c1.set()
+ assert mp is not mp3
+ # Since none of these set calls had values, the state should not be dirty
+ assert not bfss.dirty_vars
+
+ # Chained Mutating function, dirty
+ bfss.c2.set_c1r_foo("baz")
+ assert "c2" in bfss.dirty_vars
+
+
def exp_is_hydrated(state: State, is_hydrated: bool = True) -> Dict[str, Any]:
"""Expected IS_HYDRATED delta that would be emitted by HydrateMiddleware.
@@ -2454,6 +2725,7 @@ class OnLoadState(State):
num: int = 0
+ @rx.event
def test_handler(self):
"""Test handler."""
self.num += 1
@@ -2531,7 +2803,7 @@ async def test_preprocess(app_module_mock, token, test_state, expected, mocker):
assert isinstance(update, StateUpdate)
updates.append(update)
assert len(updates) == 1
- assert updates[0].delta["state"].pop("router") is not None
+ assert updates[0].delta[State.get_name()].pop("router") is not None
assert updates[0].delta == exp_is_hydrated(state, False)
events = updates[0].events
@@ -2541,6 +2813,9 @@ async def test_preprocess(app_module_mock, token, test_state, expected, mocker):
}
assert (await state._process(events[1]).__anext__()).delta == exp_is_hydrated(state)
+ if isinstance(app.state_manager, StateManagerRedis):
+ await app.state_manager.close()
+
@pytest.mark.asyncio
async def test_preprocess_multiple_load_events(app_module_mock, token, mocker):
@@ -2575,7 +2850,7 @@ async def test_preprocess_multiple_load_events(app_module_mock, token, mocker):
assert isinstance(update, StateUpdate)
updates.append(update)
assert len(updates) == 1
- assert updates[0].delta["state"].pop("router") is not None
+ assert updates[0].delta[State.get_name()].pop("router") is not None
assert updates[0].delta == exp_is_hydrated(state, False)
events = updates[0].events
@@ -2588,6 +2863,9 @@ async def test_preprocess_multiple_load_events(app_module_mock, token, mocker):
}
assert (await state._process(events[2]).__anext__()).delta == exp_is_hydrated(state)
+ if isinstance(app.state_manager, StateManagerRedis):
+ await app.state_manager.close()
+
@pytest.mark.asyncio
async def test_get_state(mock_app: rx.App, token: str):
@@ -2604,25 +2882,30 @@ async def test_get_state(mock_app: rx.App, token: str):
_substate_key(token, ChildState2)
)
assert isinstance(test_state, TestState)
- if isinstance(mock_app.state_manager, StateManagerMemory):
+ if isinstance(mock_app.state_manager, (StateManagerMemory, StateManagerDisk)):
# All substates are available
assert tuple(sorted(test_state.substates)) == (
- "child_state",
- "child_state2",
- "child_state3",
+ ChildState.get_name(),
+ ChildState2.get_name(),
+ ChildState3.get_name(),
)
else:
# Sibling states are only populated if they have computed vars
- assert tuple(sorted(test_state.substates)) == ("child_state2", "child_state3")
+ assert tuple(sorted(test_state.substates)) == (
+ ChildState2.get_name(),
+ ChildState3.get_name(),
+ )
# Because ChildState3 has a computed var, it is always dirty, and always populated.
assert (
- test_state.substates["child_state3"].substates["grandchild_state3"].computed
+ test_state.substates[ChildState3.get_name()]
+ .substates[GrandchildState3.get_name()]
+ .computed
== ""
)
# Get the child_state2 directly.
- child_state2_direct = test_state.get_substate(["child_state2"])
+ child_state2_direct = test_state.get_substate([ChildState2.get_name()])
child_state2_get_state = await test_state.get_state(ChildState2)
# These should be the same object.
assert child_state2_direct is child_state2_get_state
@@ -2633,19 +2916,21 @@ async def test_get_state(mock_app: rx.App, token: str):
# Now the original root should have all substates populated.
assert tuple(sorted(test_state.substates)) == (
- "child_state",
- "child_state2",
- "child_state3",
+ ChildState.get_name(),
+ ChildState2.get_name(),
+ ChildState3.get_name(),
)
# ChildState should be retrievable
- child_state_direct = test_state.get_substate(["child_state"])
+ child_state_direct = test_state.get_substate([ChildState.get_name()])
child_state_get_state = await test_state.get_state(ChildState)
# These should be the same object.
assert child_state_direct is child_state_get_state
# GrandchildState instance should be the same as the one retrieved from the child_state2.
- assert grandchild_state is child_state_direct.get_substate(["grandchild_state"])
+ assert grandchild_state is child_state_direct.get_substate(
+ [GrandchildState.get_name()]
+ )
grandchild_state.value2 = "set_value"
assert test_state.get_delta() == {
@@ -2666,27 +2951,27 @@ async def test_get_state(mock_app: rx.App, token: str):
_substate_key(token, ChildState2)
)
assert isinstance(new_test_state, TestState)
- if isinstance(mock_app.state_manager, StateManagerMemory):
+ if isinstance(mock_app.state_manager, (StateManagerMemory, StateManagerDisk)):
# In memory, it's the same instance
assert new_test_state is test_state
test_state._clean()
# All substates are available
assert tuple(sorted(new_test_state.substates)) == (
- "child_state",
- "child_state2",
- "child_state3",
+ ChildState.get_name(),
+ ChildState2.get_name(),
+ ChildState3.get_name(),
)
else:
# With redis, we get a whole new instance
assert new_test_state is not test_state
# Sibling states are only populated if they have computed vars
assert tuple(sorted(new_test_state.substates)) == (
- "child_state2",
- "child_state3",
+ ChildState2.get_name(),
+ ChildState3.get_name(),
)
# Set a value on child_state2, should update cached var in grandchild_state2
- child_state2 = new_test_state.get_substate(("child_state2",))
+ child_state2 = new_test_state.get_substate((ChildState2.get_name(),))
child_state2.value = "set_c2_value"
assert new_test_state.get_delta() == {
@@ -2777,8 +3062,8 @@ async def test_get_state_from_sibling_not_cached(mock_app: rx.App, token: str):
if isinstance(mock_app.state_manager, StateManagerRedis):
# When redis is used, only states with computed vars are pre-fetched.
- assert "child2" not in root.substates
- assert "child3" in root.substates # (due to @rx.var)
+ assert Child2.get_name() not in root.substates
+ assert Child3.get_name() in root.substates # (due to @rx.var)
# Get the unconnected sibling state, which will be used to `get_state` other instances.
child = root.get_substate(Child.get_full_name().split("."))
@@ -2824,6 +3109,51 @@ def test_potentially_dirty_substates():
assert C1._potentially_dirty_substates() == set()
+def test_router_var_dep() -> None:
+ """Test that router var dependencies are correctly tracked."""
+
+ class RouterVarParentState(State):
+ """A parent state for testing router var dependency."""
+
+ pass
+
+ class RouterVarDepState(RouterVarParentState):
+ """A state with a router var dependency."""
+
+ @rx.var(cache=True)
+ def foo(self) -> str:
+ return self.router.page.params.get("foo", "")
+
+ foo = RouterVarDepState.computed_vars["foo"]
+ State._init_var_dependency_dicts()
+
+ assert foo._deps(objclass=RouterVarDepState) == {"router"}
+ assert RouterVarParentState._potentially_dirty_substates() == {RouterVarDepState}
+ assert RouterVarParentState._substate_var_dependencies == {
+ "router": {RouterVarDepState.get_name()}
+ }
+ assert RouterVarDepState._computed_var_dependencies == {
+ "router": {"foo"},
+ }
+
+ rx_state = State()
+ parent_state = RouterVarParentState()
+ state = RouterVarDepState()
+
+ # link states
+ rx_state.substates = {RouterVarParentState.get_name(): parent_state}
+ parent_state.parent_state = rx_state
+ state.parent_state = parent_state
+ parent_state.substates = {RouterVarDepState.get_name(): state}
+
+ assert state.dirty_vars == set()
+
+ # Reassign router var
+ state.router = state.router
+ assert state.dirty_vars == {"foo", "router"}
+ assert parent_state.dirty_substates == {RouterVarDepState.get_name()}
+
+
@pytest.mark.asyncio
async def test_setvar(mock_app: rx.App, token: str):
"""Test that setvar works correctly.
@@ -2860,3 +3190,217 @@ async def test_setvar(mock_app: rx.App, token: str):
# Cannot setvar with non-string
with pytest.raises(ValueError):
TestState.setvar(42, 42)
+
+
+@pytest.mark.asyncio
+async def test_setvar_async_setter():
+ """Test that overridden async setters raise Exception when used with setvar."""
+ with pytest.raises(NotImplementedError):
+ TestState.setvar("asynctest", 42)
+
+
+@pytest.mark.skipif("REDIS_URL" not in os.environ, reason="Test requires redis")
+@pytest.mark.parametrize(
+ "expiration_kwargs, expected_values",
+ [
+ ({"redis_lock_expiration": 20000}, (20000, constants.Expiration.TOKEN)),
+ (
+ {"redis_lock_expiration": 50000, "redis_token_expiration": 5600},
+ (50000, 5600),
+ ),
+ ({"redis_token_expiration": 7600}, (constants.Expiration.LOCK, 7600)),
+ ],
+)
+def test_redis_state_manager_config_knobs(tmp_path, expiration_kwargs, expected_values):
+ proj_root = tmp_path / "project1"
+ proj_root.mkdir()
+
+ config_items = ",\n ".join(
+ f"{key} = {value}" for key, value in expiration_kwargs.items()
+ )
+
+ config_string = f"""
+import reflex as rx
+config = rx.Config(
+ app_name="project1",
+ redis_url="redis://localhost:6379",
+ state_manager_mode="redis",
+ {config_items}
+)
+"""
+ (proj_root / "rxconfig.py").write_text(dedent(config_string))
+
+ with chdir(proj_root):
+ # reload config for each parameter to avoid stale values
+ reflex.config.get_config(reload=True)
+ from reflex.state import State, StateManager
+
+ state_manager = StateManager.create(state=State)
+ assert state_manager.lock_expiration == expected_values[0] # type: ignore
+ assert state_manager.token_expiration == expected_values[1] # type: ignore
+
+
+class MixinState(State, mixin=True):
+ """A mixin state for testing."""
+
+ num: int = 0
+ _backend: int = 0
+ _backend_no_default: dict
+
+ @rx.var(cache=True)
+ def computed(self) -> str:
+ """A computed var on mixin state.
+
+ Returns:
+ A computed value.
+ """
+ return ""
+
+
+class UsesMixinState(MixinState, State):
+ """A state that uses the mixin state."""
+
+ pass
+
+
+class ChildUsesMixinState(UsesMixinState):
+ """A child state that uses the mixin state."""
+
+ pass
+
+
+def test_mixin_state() -> None:
+ """Test that a mixin state works correctly."""
+ assert "num" in UsesMixinState.base_vars
+ assert "num" in UsesMixinState.vars
+ assert UsesMixinState.backend_vars == {"_backend": 0, "_backend_no_default": {}}
+
+ assert "computed" in UsesMixinState.computed_vars
+ assert "computed" in UsesMixinState.vars
+
+ assert (
+ UsesMixinState(_reflex_internal_init=True)._backend_no_default # type: ignore
+ is not UsesMixinState.backend_vars["_backend_no_default"]
+ )
+
+
+def test_child_mixin_state() -> None:
+ """Test that mixin vars are only applied to the highest state in the hierarchy."""
+ assert "num" in ChildUsesMixinState.inherited_vars
+ assert "num" not in ChildUsesMixinState.base_vars
+
+ assert "computed" in ChildUsesMixinState.inherited_vars
+ assert "computed" not in ChildUsesMixinState.computed_vars
+
+
+def test_assignment_to_undeclared_vars():
+ """Test that an attribute error is thrown when undeclared vars are set."""
+
+ class State(BaseState):
+ val: str
+ _val: str
+ __val: str # type: ignore
+
+ def handle_supported_regular_vars(self):
+ self.val = "no underscore"
+ self._val = "single leading underscore"
+ self.__val = "double leading undercore"
+
+ def handle_regular_var(self):
+ self.num = 5
+
+ def handle_backend_var(self):
+ self._num = 5
+
+ def handle_non_var(self):
+ self.__num = 5
+
+ class Substate(State):
+ def handle_var(self):
+ self.value = 20
+
+ state = State() # type: ignore
+ sub_state = Substate() # type: ignore
+
+ with pytest.raises(SetUndefinedStateVarError):
+ state.handle_regular_var()
+
+ with pytest.raises(SetUndefinedStateVarError):
+ sub_state.handle_var()
+
+ with pytest.raises(SetUndefinedStateVarError):
+ state.handle_backend_var()
+
+ state.handle_supported_regular_vars()
+ state.handle_non_var()
+
+
+@pytest.mark.asyncio
+async def test_deserialize_gc_state_disk(token):
+ """Test that a state can be deserialized from disk with a grandchild state.
+
+ Args:
+ token: A token.
+ """
+
+ class Root(BaseState):
+ pass
+
+ class State(Root):
+ num: int = 42
+
+ class Child(State):
+ foo: str = "bar"
+
+ dsm = StateManagerDisk(state=Root)
+ async with dsm.modify_state(token) as root:
+ s = await root.get_state(State)
+ s.num += 1
+ c = await root.get_state(Child)
+ assert s._get_was_touched()
+ assert not c._get_was_touched()
+
+ dsm2 = StateManagerDisk(state=Root)
+ root = await dsm2.get_state(token)
+ s = await root.get_state(State)
+ assert s.num == 43
+ c = await root.get_state(Child)
+ assert c.foo == "bar"
+
+
+class Obj(Base):
+ """A object containing a callable for testing fallback pickle."""
+
+ _f: Callable
+
+
+def test_fallback_pickle():
+ """Test that state serialization will fall back to dill."""
+
+ class DillState(BaseState):
+ _o: Optional[Obj] = None
+ _f: Optional[Callable] = None
+ _g: Any = None
+
+ state = DillState(_reflex_internal_init=True) # type: ignore
+ state._o = Obj(_f=lambda: 42)
+ state._f = lambda: 420
+
+ pk = state._serialize()
+
+ unpickled_state = BaseState._deserialize(pk)
+ assert unpickled_state._f() == 420
+ assert unpickled_state._o._f() == 42
+
+ # Threading locks are unpicklable normally, and raise TypeError instead of PicklingError.
+ state2 = DillState(_reflex_internal_init=True) # type: ignore
+ state2._g = threading.Lock()
+ pk2 = state2._serialize()
+ unpickled_state2 = BaseState._deserialize(pk2)
+ assert isinstance(unpickled_state2._g, type(threading.Lock()))
+
+ # Some object, like generator, are still unpicklable with dill.
+ state3 = DillState(_reflex_internal_init=True) # type: ignore
+ state3._g = (i for i in range(10))
+ pk3 = state3._serialize()
+ assert len(pk3) == 0
diff --git a/tests/test_state_tree.py b/tests/units/test_state_tree.py
similarity index 88%
rename from tests/test_state_tree.py
rename to tests/units/test_state_tree.py
index 0747f900c..ebdd877de 100644
--- a/tests/test_state_tree.py
+++ b/tests/units/test_state_tree.py
@@ -1,8 +1,9 @@
"""Specialized test for a larger state tree."""
-import asyncio
-from typing import Generator
+
+from typing import AsyncGenerator
import pytest
+import pytest_asyncio
import reflex as rx
from reflex.state import BaseState, StateManager, StateManagerRedis, _substate_key
@@ -41,7 +42,7 @@ class SubA_A_A_A(SubA_A_A):
class SubA_A_A_B(SubA_A_A):
"""SubA_A_A_B is a child of SubA_A_A."""
- @rx.cached_var
+ @rx.var(cache=True)
def sub_a_a_a_cached(self) -> int:
"""A cached var.
@@ -182,7 +183,7 @@ class SubE_A_A_A_D(SubE_A_A_A):
sub_e_a_a_a_d: int
- @rx.cached_var
+ @rx.var(cache=True)
def sub_e_a_a_a_d_var(self) -> int:
"""A computed var.
@@ -209,8 +210,10 @@ ALWAYS_COMPUTED_DICT_KEYS = [
]
-@pytest.fixture(scope="function")
-def state_manager_redis(app_module_mock) -> Generator[StateManager, None, None]:
+@pytest_asyncio.fixture(loop_scope="function", scope="function")
+async def state_manager_redis(
+ app_module_mock,
+) -> AsyncGenerator[StateManager, None]:
"""Instance of state manager for redis only.
Args:
@@ -227,7 +230,7 @@ def state_manager_redis(app_module_mock) -> Generator[StateManager, None, None]:
yield state_manager
- asyncio.get_event_loop().run_until_complete(state_manager.close())
+ await state_manager.close()
@pytest.mark.asyncio
@@ -236,7 +239,13 @@ def state_manager_redis(app_module_mock) -> Generator[StateManager, None, None]:
[
(
Root,
- ["tree_a", "tree_b", "tree_c", "tree_d", "tree_e"],
+ [
+ TreeA.get_name(),
+ TreeB.get_name(),
+ TreeC.get_name(),
+ TreeD.get_name(),
+ TreeE.get_name(),
+ ],
[
TreeA.get_full_name(),
SubA_A.get_full_name(),
@@ -260,7 +269,7 @@ def state_manager_redis(app_module_mock) -> Generator[StateManager, None, None]:
),
(
TreeA,
- ("tree_a", "tree_d", "tree_e"),
+ (TreeA.get_name(), TreeD.get_name(), TreeE.get_name()),
[
TreeA.get_full_name(),
SubA_A.get_full_name(),
@@ -275,7 +284,7 @@ def state_manager_redis(app_module_mock) -> Generator[StateManager, None, None]:
),
(
SubA_A_A_A,
- ["tree_a", "tree_d", "tree_e"],
+ [TreeA.get_name(), TreeD.get_name(), TreeE.get_name()],
[
TreeA.get_full_name(),
SubA_A.get_full_name(),
@@ -287,7 +296,7 @@ def state_manager_redis(app_module_mock) -> Generator[StateManager, None, None]:
),
(
TreeB,
- ["tree_b", "tree_d", "tree_e"],
+ [TreeB.get_name(), TreeD.get_name(), TreeE.get_name()],
[
TreeB.get_full_name(),
SubB_A.get_full_name(),
@@ -299,7 +308,7 @@ def state_manager_redis(app_module_mock) -> Generator[StateManager, None, None]:
),
(
SubB_B,
- ["tree_b", "tree_d", "tree_e"],
+ [TreeB.get_name(), TreeD.get_name(), TreeE.get_name()],
[
TreeB.get_full_name(),
SubB_B.get_full_name(),
@@ -308,7 +317,7 @@ def state_manager_redis(app_module_mock) -> Generator[StateManager, None, None]:
),
(
SubB_C_A,
- ["tree_b", "tree_d", "tree_e"],
+ [TreeB.get_name(), TreeD.get_name(), TreeE.get_name()],
[
TreeB.get_full_name(),
SubB_C.get_full_name(),
@@ -318,7 +327,7 @@ def state_manager_redis(app_module_mock) -> Generator[StateManager, None, None]:
),
(
TreeC,
- ["tree_c", "tree_d", "tree_e"],
+ [TreeC.get_name(), TreeD.get_name(), TreeE.get_name()],
[
TreeC.get_full_name(),
SubC_A.get_full_name(),
@@ -327,14 +336,14 @@ def state_manager_redis(app_module_mock) -> Generator[StateManager, None, None]:
),
(
TreeD,
- ["tree_d", "tree_e"],
+ [TreeD.get_name(), TreeE.get_name()],
[
*ALWAYS_COMPUTED_DICT_KEYS,
],
),
(
TreeE,
- ["tree_d", "tree_e"],
+ [TreeE.get_name(), TreeD.get_name()],
[
# Extra siblings of computed var included now.
SubE_A_A_A_B.get_full_name(),
diff --git a/tests/test_style.py b/tests/units/test_style.py
similarity index 87%
rename from tests/test_style.py
rename to tests/units/test_style.py
index 825d72a9d..e1d652798 100644
--- a/tests/test_style.py
+++ b/tests/units/test_style.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from typing import Any
+from typing import Any, Dict
import pytest
@@ -8,21 +8,22 @@ import reflex as rx
from reflex import style
from reflex.components.component import evaluate_style_namespaces
from reflex.style import Style
-from reflex.vars import Var, VarData
+from reflex.vars import VarData
+from reflex.vars.base import LiteralVar, Var
test_style = [
({"a": 1}, {"a": 1}),
- ({"a": Var.create("abc")}, {"a": "abc"}),
+ ({"a": LiteralVar.create("abc")}, {"a": "abc"}),
({"test_case": 1}, {"testCase": 1}),
- ({"test_case": {"a": 1}}, {"testCase": {"a": 1}}),
- ({":test_case": {"a": 1}}, {":testCase": {"a": 1}}),
- ({"::test_case": {"a": 1}}, {"::testCase": {"a": 1}}),
+ ({"test_case": {"a": 1}}, {"test_case": {"a": 1}}),
+ ({":test_case": {"a": 1}}, {":test_case": {"a": 1}}),
+ ({"::test_case": {"a": 1}}, {"::test_case": {"a": 1}}),
(
{"::-webkit-scrollbar": {"display": "none"}},
{"::-webkit-scrollbar": {"display": "none"}},
),
- ({"margin_y": "2rem"}, {"marginBottom": "2rem", "marginTop": "2rem"}),
- ({"marginY": "2rem"}, {"marginBottom": "2rem", "marginTop": "2rem"}),
+ ({"margin_y": "2rem"}, {"marginTop": "2rem", "marginBottom": "2rem"}),
+ ({"marginY": "2rem"}, {"marginTop": "2rem", "marginBottom": "2rem"}),
(
{"::-webkit-scrollbar": {"bgColor": "red"}},
{"::-webkit-scrollbar": {"backgroundColor": "red"}},
@@ -49,7 +50,7 @@ def test_convert(style_dict, expected):
expected: The expected formatted style.
"""
converted_dict, _var_data = style.convert(style_dict)
- assert converted_dict == expected
+ assert LiteralVar.create(converted_dict).equals(LiteralVar.create(expected))
@pytest.mark.parametrize(
@@ -63,7 +64,9 @@ def test_create_style(style_dict, expected):
style_dict: The style to check.
expected: The expected formatted style.
"""
- assert style.Style(style_dict) == expected
+ assert LiteralVar.create(style.Style(style_dict)).equals(
+ LiteralVar.create(expected)
+ )
def compare_dict_of_var(d1: dict[str, Any], d2: dict[str, Any]):
@@ -87,39 +90,47 @@ def compare_dict_of_var(d1: dict[str, Any], d2: dict[str, Any]):
@pytest.mark.parametrize(
("kwargs", "style_dict", "expected_get_style"),
[
- ({}, {}, {"css": None}),
- ({"color": "hotpink"}, {}, {"css": Var.create(Style({"color": "hotpink"}))}),
- ({}, {"color": "red"}, {"css": Var.create(Style({"color": "red"}))}),
+ ({}, {}, {}),
+ (
+ {"color": "hotpink"},
+ {},
+ {"css": LiteralVar.create(Style({"color": "hotpink"}))},
+ ),
+ ({}, {"color": "red"}, {"css": LiteralVar.create(Style({"color": "red"}))}),
(
{"color": "hotpink"},
{"color": "red"},
- {"css": Var.create(Style({"color": "hotpink"}))},
+ {"css": LiteralVar.create(Style({"color": "hotpink"}))},
),
(
{"_hover": {"color": "hotpink"}},
{},
- {"css": Var.create(Style({"&:hover": {"color": "hotpink"}}))},
+ {"css": LiteralVar.create(Style({"&:hover": {"color": "hotpink"}}))},
),
(
{},
{"_hover": {"color": "red"}},
- {"css": Var.create(Style({"&:hover": {"color": "red"}}))},
+ {"css": LiteralVar.create(Style({"&:hover": {"color": "red"}}))},
),
(
{},
{":hover": {"color": "red"}},
- {"css": Var.create(Style({"&:hover": {"color": "red"}}))},
+ {"css": LiteralVar.create(Style({"&:hover": {"color": "red"}}))},
),
(
{},
{"::-webkit-scrollbar": {"display": "none"}},
- {"css": Var.create(Style({"&::-webkit-scrollbar": {"display": "none"}}))},
+ {
+ "css": LiteralVar.create(
+ Style({"&::-webkit-scrollbar": {"display": "none"}})
+ )
+ },
),
(
{},
{"::-moz-progress-bar": {"background_color": "red"}},
{
- "css": Var.create(
+ "css": LiteralVar.create(
Style({"&::-moz-progress-bar": {"backgroundColor": "red"}})
)
},
@@ -128,7 +139,7 @@ def compare_dict_of_var(d1: dict[str, Any], d2: dict[str, Any]):
{"color": ["#111", "#222", "#333", "#444", "#555"]},
{},
{
- "css": Var.create(
+ "css": LiteralVar.create(
Style(
{
"@media screen and (min-width: 0)": {"color": "#111"},
@@ -148,7 +159,7 @@ def compare_dict_of_var(d1: dict[str, Any], d2: dict[str, Any]):
},
{},
{
- "css": Var.create(
+ "css": LiteralVar.create(
Style(
{
"@media screen and (min-width: 0)": {"color": "#111"},
@@ -169,7 +180,7 @@ def compare_dict_of_var(d1: dict[str, Any], d2: dict[str, Any]):
},
{},
{
- "css": Var.create(
+ "css": LiteralVar.create(
Style(
{
"@media screen and (min-width: 0)": {
@@ -209,7 +220,7 @@ def compare_dict_of_var(d1: dict[str, Any], d2: dict[str, Any]):
},
{},
{
- "css": Var.create(
+ "css": LiteralVar.create(
Style(
{
"&:hover": {
@@ -236,7 +247,7 @@ def compare_dict_of_var(d1: dict[str, Any], d2: dict[str, Any]):
{"_hover": {"color": ["#111", "#222", "#333", "#444", "#555"]}},
{},
{
- "css": Var.create(
+ "css": LiteralVar.create(
Style(
{
"&:hover": {
@@ -268,7 +279,7 @@ def compare_dict_of_var(d1: dict[str, Any], d2: dict[str, Any]):
},
{},
{
- "css": Var.create(
+ "css": LiteralVar.create(
Style(
{
"&:hover": {
@@ -307,7 +318,7 @@ def compare_dict_of_var(d1: dict[str, Any], d2: dict[str, Any]):
},
{},
{
- "css": Var.create(
+ "css": LiteralVar.create(
Style(
{
"&:hover": {
@@ -361,20 +372,20 @@ class StyleState(rx.State):
[
(
{"color": StyleState.color},
- {"css": Var.create(Style({"color": StyleState.color}))},
+ {"css": LiteralVar.create(Style({"color": StyleState.color}))},
),
(
{"color": f"dark{StyleState.color}"},
{
- "css": Var.create_safe(f'{{"color": `dark{StyleState.color}`}}').to(
- Style
- )
+ "css": Var(
+ _js_expr=f'({{ ["color"] : ("dark"+{StyleState.color}) }})'
+ ).to(Dict[str, str])
},
),
(
{"color": StyleState.color, "_hover": {"color": StyleState.color2}},
{
- "css": Var.create(
+ "css": LiteralVar.create(
Style(
{
"color": StyleState.color,
@@ -387,7 +398,7 @@ class StyleState(rx.State):
(
{"color": [StyleState.color, "gray", StyleState.color2, "yellow", "blue"]},
{
- "css": Var.create(
+ "css": LiteralVar.create(
Style(
{
"@media screen and (min-width: 0)": {
@@ -415,7 +426,7 @@ class StyleState(rx.State):
]
},
{
- "css": Var.create(
+ "css": LiteralVar.create(
Style(
{
"&:hover": {
@@ -453,7 +464,7 @@ class StyleState(rx.State):
}
},
{
- "css": Var.create(
+ "css": LiteralVar.create(
Style(
{
"&:hover": {
@@ -492,7 +503,10 @@ def test_style_via_component_with_state(
"""
comp = rx.el.div(**kwargs)
- assert comp.style._var_data == expected_get_style["css"]._var_data
+ assert (
+ VarData.merge(comp.style._var_data)
+ == expected_get_style["css"]._get_all_var_data()
+ )
# Assert that style values are equal.
compare_dict_of_var(comp._get_style(), expected_get_style)
@@ -507,10 +521,10 @@ def test_evaluate_style_namespaces():
def test_style_update_with_var_data():
"""Test that .update with a Style containing VarData works."""
- red_var = Var.create_safe("red")._replace(
+ red_var = LiteralVar.create("red")._replace(
merge_var_data=VarData(hooks={"const red = true": None}), # type: ignore
)
- blue_var = Var.create_safe("blue", _var_is_local=False)._replace(
+ blue_var = LiteralVar.create("blue")._replace(
merge_var_data=VarData(hooks={"const blue = true": None}), # type: ignore
)
@@ -521,7 +535,9 @@ def test_style_update_with_var_data():
)
s2 = Style()
s2.update(s1, background_color=f"{blue_var}ish")
- assert s2 == {"color": "red", "backgroundColor": "`${blue}ish`"}
+ assert str(LiteralVar.create(s2)) == str(
+ LiteralVar.create({"color": "red", "backgroundColor": "blueish"})
+ )
assert s2._var_data is not None
assert "const red = true" in s2._var_data.hooks
assert "const blue = true" in s2._var_data.hooks
diff --git a/tests/test_telemetry.py b/tests/units/test_telemetry.py
similarity index 64%
rename from tests/test_telemetry.py
rename to tests/units/test_telemetry.py
index 58786c67b..25ad91323 100644
--- a/tests/test_telemetry.py
+++ b/tests/units/test_telemetry.py
@@ -1,4 +1,3 @@
-import httpx
import pytest
from packaging.version import parse as parse_python_version
@@ -29,25 +28,28 @@ def test_telemetry():
def test_disable():
"""Test that disabling telemetry works."""
- assert not telemetry.send("test", telemetry_enabled=False)
+ assert not telemetry._send("test", telemetry_enabled=False)
@pytest.mark.parametrize("event", ["init", "reinit", "run-dev", "run-prod", "export"])
def test_send(mocker, event):
- mocker.patch("httpx.post")
- mocker.patch(
- "builtins.open",
- mocker.mock_open(
- read_data='{"project_hash": "78285505863498957834586115958872998605"}'
- ),
+ httpx_post_mock = mocker.patch("httpx.post")
+ # mocker.patch(
+ # "builtins.open",
+ # mocker.mock_open(
+ # read_data='{"project_hash": "78285505863498957834586115958872998605"}'
+ # ),
+ # )
+
+ # Mock the read_text method of Path
+ pathlib_path_read_text_mock = mocker.patch(
+ "pathlib.Path.read_text",
+ return_value='{"project_hash": "78285505863498957834586115958872998605"}',
)
+
mocker.patch("platform.platform", return_value="Mocked Platform")
- telemetry.send(event, telemetry_enabled=True)
- httpx.post.assert_called_once()
- if telemetry.get_os() == "Windows":
- open.assert_called_with(".web\\reflex.json", "r")
- elif telemetry.get_os() == "Linux":
- open.assert_called_with("/proc/meminfo", "rb", buffering=32768)
- else:
- open.assert_called_with(".web/reflex.json", "r")
+ telemetry._send(event, telemetry_enabled=True)
+ httpx_post_mock.assert_called_once()
+
+ assert pathlib_path_read_text_mock.call_count == 2
diff --git a/tests/test_testing.py b/tests/units/test_testing.py
similarity index 99%
rename from tests/test_testing.py
rename to tests/units/test_testing.py
index c53e9e775..b01709202 100644
--- a/tests/test_testing.py
+++ b/tests/units/test_testing.py
@@ -1,4 +1,5 @@
"""Unit tests for the included testing tools."""
+
import pytest
from reflex.constants import IS_WINDOWS
diff --git a/tests/units/test_var.py b/tests/units/test_var.py
new file mode 100644
index 000000000..a8b4b759d
--- /dev/null
+++ b/tests/units/test_var.py
@@ -0,0 +1,1853 @@
+import json
+import math
+import sys
+import typing
+from typing import Dict, List, Optional, Set, Tuple, Union, cast
+
+import pytest
+from pandas import DataFrame
+
+import reflex as rx
+from reflex.base import Base
+from reflex.constants.base import REFLEX_VAR_CLOSING_TAG, REFLEX_VAR_OPENING_TAG
+from reflex.state import BaseState
+from reflex.utils.exceptions import PrimitiveUnserializableToJSON
+from reflex.utils.imports import ImportVar
+from reflex.vars import VarData
+from reflex.vars.base import (
+ ComputedVar,
+ LiteralVar,
+ Var,
+ computed_var,
+ var_operation,
+ var_operation_return,
+)
+from reflex.vars.function import ArgsFunctionOperation, FunctionStringVar
+from reflex.vars.number import (
+ LiteralBooleanVar,
+ LiteralNumberVar,
+ NumberVar,
+)
+from reflex.vars.object import LiteralObjectVar, ObjectVar
+from reflex.vars.sequence import (
+ ArrayVar,
+ ConcatVarOperation,
+ LiteralArrayVar,
+ LiteralStringVar,
+)
+
+test_vars = [
+ Var(_js_expr="prop1", _var_type=int),
+ Var(_js_expr="key", _var_type=str),
+ Var(_js_expr="value", _var_type=str)._var_set_state("state"),
+ Var(_js_expr="local", _var_type=str)._var_set_state("state"),
+ Var(_js_expr="local2", _var_type=str),
+]
+
+
+class ATestState(BaseState):
+ """Test state."""
+
+ value: str
+ dict_val: Dict[str, List] = {}
+
+
+@pytest.fixture
+def TestObj():
+ class TestObj(Base):
+ foo: int
+ bar: str
+
+ return TestObj
+
+
+@pytest.fixture
+def ParentState(TestObj):
+ class ParentState(BaseState):
+ foo: int
+ bar: int
+
+ @computed_var
+ def var_without_annotation(self):
+ return TestObj
+
+ return ParentState
+
+
+@pytest.fixture
+def ChildState(ParentState, TestObj):
+ class ChildState(ParentState):
+ @computed_var
+ def var_without_annotation(self):
+ """This shadows ParentState.var_without_annotation.
+
+ Returns:
+ TestObj: Test object.
+ """
+ return TestObj
+
+ return ChildState
+
+
+@pytest.fixture
+def GrandChildState(ChildState, TestObj):
+ class GrandChildState(ChildState):
+ @computed_var
+ def var_without_annotation(self):
+ """This shadows ChildState.var_without_annotation.
+
+ Returns:
+ TestObj: Test object.
+ """
+ return TestObj
+
+ return GrandChildState
+
+
+@pytest.fixture
+def StateWithAnyVar(TestObj):
+ class StateWithAnyVar(BaseState):
+ @computed_var
+ def var_without_annotation(self) -> typing.Any:
+ return TestObj
+
+ return StateWithAnyVar
+
+
+@pytest.fixture
+def StateWithCorrectVarAnnotation():
+ class StateWithCorrectVarAnnotation(BaseState):
+ @computed_var
+ def var_with_annotation(self) -> str:
+ return "Correct annotation"
+
+ return StateWithCorrectVarAnnotation
+
+
+@pytest.fixture
+def StateWithWrongVarAnnotation(TestObj):
+ class StateWithWrongVarAnnotation(BaseState):
+ @computed_var
+ def var_with_annotation(self) -> str:
+ return TestObj
+
+ return StateWithWrongVarAnnotation
+
+
+@pytest.fixture
+def StateWithInitialComputedVar():
+ class StateWithInitialComputedVar(BaseState):
+ @computed_var(initial_value="Initial value")
+ def var_with_initial_value(self) -> str:
+ return "Runtime value"
+
+ return StateWithInitialComputedVar
+
+
+@pytest.fixture
+def ChildWithInitialComputedVar(StateWithInitialComputedVar):
+ class ChildWithInitialComputedVar(StateWithInitialComputedVar):
+ @computed_var(initial_value="Initial value")
+ def var_with_initial_value_child(self) -> str:
+ return "Runtime value"
+
+ return ChildWithInitialComputedVar
+
+
+@pytest.fixture
+def StateWithRuntimeOnlyVar():
+ class StateWithRuntimeOnlyVar(BaseState):
+ @computed_var(initial_value=None)
+ def var_raises_at_runtime(self) -> str:
+ raise ValueError("So nicht, mein Freund")
+
+ return StateWithRuntimeOnlyVar
+
+
+@pytest.fixture
+def ChildWithRuntimeOnlyVar(StateWithRuntimeOnlyVar):
+ class ChildWithRuntimeOnlyVar(StateWithRuntimeOnlyVar):
+ @computed_var(initial_value="Initial value")
+ def var_raises_at_runtime_child(self) -> str:
+ raise ValueError("So nicht, mein Freund")
+
+ return ChildWithRuntimeOnlyVar
+
+
+@pytest.mark.parametrize(
+ "prop,expected",
+ zip(
+ test_vars,
+ [
+ "prop1",
+ "key",
+ "state.value",
+ "state.local",
+ "local2",
+ ],
+ ),
+)
+def test_full_name(prop, expected):
+ """Test that the full name of a var is correct.
+
+ Args:
+ prop: The var to test.
+ expected: The expected full name.
+ """
+ assert str(prop) == expected
+
+
+@pytest.mark.parametrize(
+ "prop,expected",
+ zip(
+ test_vars,
+ ["prop1", "key", "state.value", "state.local", "local2"],
+ ),
+)
+def test_str(prop, expected):
+ """Test that the string representation of a var is correct.
+
+ Args:
+ prop: The var to test.
+ expected: The expected string representation.
+ """
+ assert str(prop) == expected
+
+
+@pytest.mark.parametrize(
+ "prop,expected",
+ [
+ (Var(_js_expr="p", _var_type=int), 0),
+ (Var(_js_expr="p", _var_type=float), 0.0),
+ (Var(_js_expr="p", _var_type=str), ""),
+ (Var(_js_expr="p", _var_type=bool), False),
+ (Var(_js_expr="p", _var_type=list), []),
+ (Var(_js_expr="p", _var_type=dict), {}),
+ (Var(_js_expr="p", _var_type=tuple), ()),
+ (Var(_js_expr="p", _var_type=set), set()),
+ ],
+)
+def test_default_value(prop, expected):
+ """Test that the default value of a var is correct.
+
+ Args:
+ prop: The var to test.
+ expected: The expected default value.
+ """
+ assert prop.get_default_value() == expected
+
+
+@pytest.mark.parametrize(
+ "prop,expected",
+ zip(
+ test_vars,
+ [
+ "set_prop1",
+ "set_key",
+ "state.set_value",
+ "state.set_local",
+ "set_local2",
+ ],
+ ),
+)
+def test_get_setter(prop, expected):
+ """Test that the name of the setter function of a var is correct.
+
+ Args:
+ prop: The var to test.
+ expected: The expected name of the setter function.
+ """
+ assert prop.get_setter_name() == expected
+
+
+@pytest.mark.parametrize(
+ "value,expected",
+ [
+ (None, Var(_js_expr="null", _var_type=None)),
+ (1, Var(_js_expr="1", _var_type=int)),
+ ("key", Var(_js_expr='"key"', _var_type=str)),
+ (3.14, Var(_js_expr="3.14", _var_type=float)),
+ ([1, 2, 3], Var(_js_expr="[1, 2, 3]", _var_type=List[int])),
+ (
+ {"a": 1, "b": 2},
+ Var(_js_expr='({ ["a"] : 1, ["b"] : 2 })', _var_type=Dict[str, int]),
+ ),
+ ],
+)
+def test_create(value, expected):
+ """Test the var create function.
+
+ Args:
+ value: The value to create a var from.
+ expected: The expected name of the setter function.
+ """
+ prop = LiteralVar.create(value)
+ assert prop.equals(expected) # type: ignore
+
+
+def test_create_type_error():
+ """Test the var create function when inputs type error."""
+
+ class ErrorType:
+ pass
+
+ value = ErrorType()
+
+ with pytest.raises(TypeError):
+ LiteralVar.create(value)
+
+
+def v(value) -> Var:
+ return LiteralVar.create(value)
+
+
+def test_basic_operations(TestObj):
+ """Test the var operations.
+
+ Args:
+ TestObj: The test object.
+ """
+ assert str(v(1) == v(2)) == "(1 === 2)"
+ assert str(v(1) != v(2)) == "(1 !== 2)"
+ assert str(LiteralNumberVar.create(1) < 2) == "(1 < 2)"
+ assert str(LiteralNumberVar.create(1) <= 2) == "(1 <= 2)"
+ assert str(LiteralNumberVar.create(1) > 2) == "(1 > 2)"
+ assert str(LiteralNumberVar.create(1) >= 2) == "(1 >= 2)"
+ assert str(LiteralNumberVar.create(1) + 2) == "(1 + 2)"
+ assert str(LiteralNumberVar.create(1) - 2) == "(1 - 2)"
+ assert str(LiteralNumberVar.create(1) * 2) == "(1 * 2)"
+ assert str(LiteralNumberVar.create(1) / 2) == "(1 / 2)"
+ assert str(LiteralNumberVar.create(1) // 2) == "Math.floor(1 / 2)"
+ assert str(LiteralNumberVar.create(1) % 2) == "(1 % 2)"
+ assert str(LiteralNumberVar.create(1) ** 2) == "(1 ** 2)"
+ assert str(LiteralNumberVar.create(1) & v(2)) == "(1 && 2)"
+ assert str(LiteralNumberVar.create(1) | v(2)) == "(1 || 2)"
+ assert str(LiteralArrayVar.create([1, 2, 3])[0]) == "[1, 2, 3].at(0)"
+ assert (
+ str(LiteralObjectVar.create({"a": 1, "b": 2})["a"])
+ == '({ ["a"] : 1, ["b"] : 2 })["a"]'
+ )
+ assert str(v("foo") == v("bar")) == '("foo" === "bar")'
+ assert str(Var(_js_expr="foo") == Var(_js_expr="bar")) == "(foo === bar)"
+ assert (
+ str(LiteralVar.create("foo") == LiteralVar.create("bar")) == '("foo" === "bar")'
+ )
+ print(Var(_js_expr="foo").to(ObjectVar, TestObj)._var_set_state("state"))
+ assert (
+ str(
+ Var(_js_expr="foo").to(ObjectVar, TestObj)._var_set_state("state").bar
+ == LiteralVar.create("bar")
+ )
+ == '(state.foo["bar"] === "bar")'
+ )
+ assert (
+ str(Var(_js_expr="foo").to(ObjectVar, TestObj)._var_set_state("state").bar)
+ == 'state.foo["bar"]'
+ )
+ assert str(abs(LiteralNumberVar.create(1))) == "Math.abs(1)"
+ assert str(LiteralArrayVar.create([1, 2, 3]).length()) == "[1, 2, 3].length"
+ assert (
+ str(LiteralArrayVar.create([1, 2]) + LiteralArrayVar.create([3, 4]))
+ == "[...[1, 2], ...[3, 4]]"
+ )
+
+ # Tests for reverse operation
+ assert (
+ str(LiteralArrayVar.create([1, 2, 3]).reverse())
+ == "[1, 2, 3].slice().reverse()"
+ )
+ assert (
+ str(LiteralArrayVar.create(["1", "2", "3"]).reverse())
+ == '["1", "2", "3"].slice().reverse()'
+ )
+ assert (
+ str(Var(_js_expr="foo")._var_set_state("state").to(list).reverse())
+ == "state.foo.slice().reverse()"
+ )
+ assert str(Var(_js_expr="foo").to(list).reverse()) == "foo.slice().reverse()"
+ assert str(Var(_js_expr="foo", _var_type=str).js_type()) == "(typeof(foo))"
+
+
+@pytest.mark.parametrize(
+ "var, expected",
+ [
+ (v([1, 2, 3]), "[1, 2, 3]"),
+ (v(set([1, 2, 3])), "[1, 2, 3]"),
+ (v(["1", "2", "3"]), '["1", "2", "3"]'),
+ (
+ Var(_js_expr="foo")._var_set_state("state").to(list),
+ "state.foo",
+ ),
+ (Var(_js_expr="foo").to(list), "foo"),
+ (v((1, 2, 3)), "[1, 2, 3]"),
+ (v(("1", "2", "3")), '["1", "2", "3"]'),
+ (
+ Var(_js_expr="foo")._var_set_state("state").to(tuple),
+ "state.foo",
+ ),
+ (Var(_js_expr="foo").to(tuple), "foo"),
+ ],
+)
+def test_list_tuple_contains(var, expected):
+ assert str(var.contains(1)) == f"{expected}.includes(1)"
+ assert str(var.contains("1")) == f'{expected}.includes("1")'
+ assert str(var.contains(v(1))) == f"{expected}.includes(1)"
+ assert str(var.contains(v("1"))) == f'{expected}.includes("1")'
+ other_state_var = Var(_js_expr="other", _var_type=str)._var_set_state("state")
+ other_var = Var(_js_expr="other", _var_type=str)
+ assert str(var.contains(other_state_var)) == f"{expected}.includes(state.other)"
+ assert str(var.contains(other_var)) == f"{expected}.includes(other)"
+
+
+class Foo(rx.Base):
+ """Foo class."""
+
+ bar: int
+ baz: str
+
+
+class Bar(rx.Base):
+ """Bar class."""
+
+ bar: str
+ baz: str
+ foo: int
+
+
+@pytest.mark.parametrize(
+ ("var", "var_type"),
+ (
+ [
+ (Var(_js_expr="", _var_type=Foo | Bar).guess_type(), Foo | Bar),
+ (Var(_js_expr="", _var_type=Foo | Bar).guess_type().bar, Union[int, str]),
+ ]
+ if sys.version_info >= (3, 10)
+ else []
+ )
+ + [
+ (Var(_js_expr="", _var_type=Union[Foo, Bar]).guess_type(), Union[Foo, Bar]),
+ (Var(_js_expr="", _var_type=Union[Foo, Bar]).guess_type().baz, str),
+ (
+ Var(_js_expr="", _var_type=Union[Foo, Bar]).guess_type().foo,
+ Union[int, None],
+ ),
+ ],
+)
+def test_var_types(var, var_type):
+ assert var._var_type == var_type
+
+
+@pytest.mark.parametrize(
+ "var, expected",
+ [
+ (v("123"), json.dumps("123")),
+ (Var(_js_expr="foo")._var_set_state("state").to(str), "state.foo"),
+ (Var(_js_expr="foo").to(str), "foo"),
+ ],
+)
+def test_str_contains(var, expected):
+ assert str(var.contains("1")) == f'{expected}.includes("1")'
+ assert str(var.contains(v("1"))) == f'{expected}.includes("1")'
+ other_state_var = Var(_js_expr="other")._var_set_state("state").to(str)
+ other_var = Var(_js_expr="other").to(str)
+ assert str(var.contains(other_state_var)) == f"{expected}.includes(state.other)"
+ assert str(var.contains(other_var)) == f"{expected}.includes(other)"
+ assert (
+ str(var.contains("1", "hello"))
+ == f'{expected}.some(obj => obj["hello"] === "1")'
+ )
+
+
+@pytest.mark.parametrize(
+ "var, expected",
+ [
+ (v({"a": 1, "b": 2}), '({ ["a"] : 1, ["b"] : 2 })'),
+ (Var(_js_expr="foo")._var_set_state("state").to(dict), "state.foo"),
+ (Var(_js_expr="foo").to(dict), "foo"),
+ ],
+)
+def test_dict_contains(var, expected):
+ assert str(var.contains(1)) == f"{expected}.hasOwnProperty(1)"
+ assert str(var.contains("1")) == f'{expected}.hasOwnProperty("1")'
+ assert str(var.contains(v(1))) == f"{expected}.hasOwnProperty(1)"
+ assert str(var.contains(v("1"))) == f'{expected}.hasOwnProperty("1")'
+ other_state_var = Var(_js_expr="other")._var_set_state("state").to(str)
+ other_var = Var(_js_expr="other").to(str)
+ assert (
+ str(var.contains(other_state_var)) == f"{expected}.hasOwnProperty(state.other)"
+ )
+ assert str(var.contains(other_var)) == f"{expected}.hasOwnProperty(other)"
+
+
+@pytest.mark.parametrize(
+ "var",
+ [
+ Var(_js_expr="list", _var_type=List[int]).guess_type(),
+ Var(_js_expr="tuple", _var_type=Tuple[int, int]).guess_type(),
+ Var(_js_expr="str", _var_type=str).guess_type(),
+ ],
+)
+def test_var_indexing_lists(var):
+ """Test that we can index into str, list or tuple vars.
+
+ Args:
+ var : The str, list or tuple base var.
+ """
+ # Test basic indexing.
+ assert str(var[0]) == f"{var._js_expr}.at(0)"
+ assert str(var[1]) == f"{var._js_expr}.at(1)"
+
+ # Test negative indexing.
+ assert str(var[-1]) == f"{var._js_expr}.at(-1)"
+
+
+@pytest.mark.parametrize(
+ "var, type_",
+ [
+ (Var(_js_expr="list", _var_type=List[int]).guess_type(), [int, int]),
+ (
+ Var(_js_expr="tuple", _var_type=Tuple[int, str]).guess_type(),
+ [int, str],
+ ),
+ ],
+)
+def test_var_indexing_types(var, type_):
+ """Test that indexing returns valid types.
+
+ Args:
+ var : The list, typle base var.
+ type_ : The type on indexed object.
+
+ """
+ assert var[0]._var_type == type_[0]
+ assert var[1]._var_type == type_[1]
+
+
+def test_var_indexing_str():
+ """Test that we can index into str vars."""
+ str_var = Var(_js_expr="str").to(str)
+
+ # Test that indexing gives a type of Var[str].
+ assert isinstance(str_var[0], Var)
+ assert str_var[0]._var_type is str
+
+ # Test basic indexing.
+ assert str(str_var[0]) == "str.at(0)"
+ assert str(str_var[1]) == "str.at(1)"
+
+ # Test negative indexing.
+ assert str(str_var[-1]) == "str.at(-1)"
+
+
+@pytest.mark.parametrize(
+ "var",
+ [
+ (Var(_js_expr="foo", _var_type=int).guess_type()),
+ (Var(_js_expr="bar", _var_type=float).guess_type()),
+ ],
+)
+def test_var_replace_with_invalid_kwargs(var):
+ with pytest.raises(TypeError) as excinfo:
+ var._replace(_this_should_fail=True)
+ assert "unexpected keyword argument" in str(excinfo.value)
+
+
+def test_computed_var_replace_with_invalid_kwargs():
+ @computed_var(initial_value=1)
+ def test_var(state) -> int:
+ return 1
+
+ with pytest.raises(TypeError) as excinfo:
+ test_var._replace(_random_kwarg=True)
+ assert "Unexpected keyword argument" in str(excinfo.value)
+
+
+@pytest.mark.parametrize(
+ "var, index",
+ [
+ (Var(_js_expr="lst", _var_type=List[int]).guess_type(), [1, 2]),
+ (
+ Var(_js_expr="lst", _var_type=List[int]).guess_type(),
+ {"name": "dict"},
+ ),
+ (Var(_js_expr="lst", _var_type=List[int]).guess_type(), {"set"}),
+ (
+ Var(_js_expr="lst", _var_type=List[int]).guess_type(),
+ (
+ 1,
+ 2,
+ ),
+ ),
+ (Var(_js_expr="lst", _var_type=List[int]).guess_type(), 1.5),
+ (Var(_js_expr="lst", _var_type=List[int]).guess_type(), "str"),
+ (
+ Var(_js_expr="lst", _var_type=List[int]).guess_type(),
+ Var(_js_expr="string_var", _var_type=str).guess_type(),
+ ),
+ (
+ Var(_js_expr="lst", _var_type=List[int]).guess_type(),
+ Var(_js_expr="float_var", _var_type=float).guess_type(),
+ ),
+ (
+ Var(_js_expr="lst", _var_type=List[int]).guess_type(),
+ Var(_js_expr="list_var", _var_type=List[int]).guess_type(),
+ ),
+ (
+ Var(_js_expr="lst", _var_type=List[int]).guess_type(),
+ Var(_js_expr="set_var", _var_type=Set[str]).guess_type(),
+ ),
+ (
+ Var(_js_expr="lst", _var_type=List[int]).guess_type(),
+ Var(_js_expr="dict_var", _var_type=Dict[str, str]).guess_type(),
+ ),
+ (Var(_js_expr="str", _var_type=str).guess_type(), [1, 2]),
+ (Var(_js_expr="lst", _var_type=str).guess_type(), {"name": "dict"}),
+ (Var(_js_expr="lst", _var_type=str).guess_type(), {"set"}),
+ (
+ Var(_js_expr="lst", _var_type=str).guess_type(),
+ Var(_js_expr="string_var", _var_type=str).guess_type(),
+ ),
+ (
+ Var(_js_expr="lst", _var_type=str).guess_type(),
+ Var(_js_expr="float_var", _var_type=float).guess_type(),
+ ),
+ (Var(_js_expr="str", _var_type=Tuple[str]).guess_type(), [1, 2]),
+ (
+ Var(_js_expr="lst", _var_type=Tuple[str]).guess_type(),
+ {"name": "dict"},
+ ),
+ (Var(_js_expr="lst", _var_type=Tuple[str]).guess_type(), {"set"}),
+ (
+ Var(_js_expr="lst", _var_type=Tuple[str]).guess_type(),
+ Var(_js_expr="string_var", _var_type=str).guess_type(),
+ ),
+ (
+ Var(_js_expr="lst", _var_type=Tuple[str]).guess_type(),
+ Var(_js_expr="float_var", _var_type=float).guess_type(),
+ ),
+ ],
+)
+def test_var_unsupported_indexing_lists(var, index):
+ """Test unsupported indexing throws a type error.
+
+ Args:
+ var: The base var.
+ index: The base var index.
+ """
+ with pytest.raises(TypeError):
+ var[index]
+
+
+@pytest.mark.parametrize(
+ "var",
+ [
+ Var(_js_expr="lst", _var_type=List[int]).guess_type(),
+ Var(_js_expr="tuple", _var_type=Tuple[int, int]).guess_type(),
+ ],
+)
+def test_var_list_slicing(var):
+ """Test that we can slice into str, list or tuple vars.
+
+ Args:
+ var : The str, list or tuple base var.
+ """
+ assert str(var[:1]) == f"{var._js_expr}.slice(undefined, 1)"
+ assert str(var[1:]) == f"{var._js_expr}.slice(1, undefined)"
+ assert str(var[:]) == f"{var._js_expr}.slice(undefined, undefined)"
+
+
+def test_str_var_slicing():
+ """Test that we can slice into str vars."""
+ str_var = Var(_js_expr="str").to(str)
+
+ # Test that slicing gives a type of Var[str].
+ assert isinstance(str_var[:1], Var)
+ assert str_var[:1]._var_type is str
+
+ # Test basic slicing.
+ assert str(str_var[:1]) == 'str.split("").slice(undefined, 1).join("")'
+ assert str(str_var[1:]) == 'str.split("").slice(1, undefined).join("")'
+ assert str(str_var[:]) == 'str.split("").slice(undefined, undefined).join("")'
+ assert str(str_var[1:2]) == 'str.split("").slice(1, 2).join("")'
+
+ # Test negative slicing.
+ assert str(str_var[:-1]) == 'str.split("").slice(undefined, -1).join("")'
+ assert str(str_var[-1:]) == 'str.split("").slice(-1, undefined).join("")'
+ assert str(str_var[:-2]) == 'str.split("").slice(undefined, -2).join("")'
+ assert str(str_var[-2:]) == 'str.split("").slice(-2, undefined).join("")'
+
+
+def test_dict_indexing():
+ """Test that we can index into dict vars."""
+ dct = Var(_js_expr="dct").to(ObjectVar, Dict[str, str])
+
+ # Check correct indexing.
+ assert str(dct["a"]) == 'dct["a"]'
+ assert str(dct["asdf"]) == 'dct["asdf"]'
+
+
+@pytest.mark.parametrize(
+ "var, index",
+ [
+ (
+ Var(_js_expr="dict", _var_type=Dict[str, str]).guess_type(),
+ [1, 2],
+ ),
+ (
+ Var(_js_expr="dict", _var_type=Dict[str, str]).guess_type(),
+ {"name": "dict"},
+ ),
+ (
+ Var(_js_expr="dict", _var_type=Dict[str, str]).guess_type(),
+ {"set"},
+ ),
+ (
+ Var(_js_expr="dict", _var_type=Dict[str, str]).guess_type(),
+ (
+ 1,
+ 2,
+ ),
+ ),
+ (
+ Var(_js_expr="lst", _var_type=Dict[str, str]).guess_type(),
+ Var(_js_expr="list_var", _var_type=List[int]).guess_type(),
+ ),
+ (
+ Var(_js_expr="lst", _var_type=Dict[str, str]).guess_type(),
+ Var(_js_expr="set_var", _var_type=Set[str]).guess_type(),
+ ),
+ (
+ Var(_js_expr="lst", _var_type=Dict[str, str]).guess_type(),
+ Var(_js_expr="dict_var", _var_type=Dict[str, str]).guess_type(),
+ ),
+ (
+ Var(_js_expr="df", _var_type=DataFrame).guess_type(),
+ [1, 2],
+ ),
+ (
+ Var(_js_expr="df", _var_type=DataFrame).guess_type(),
+ {"name": "dict"},
+ ),
+ (
+ Var(_js_expr="df", _var_type=DataFrame).guess_type(),
+ {"set"},
+ ),
+ (
+ Var(_js_expr="df", _var_type=DataFrame).guess_type(),
+ (
+ 1,
+ 2,
+ ),
+ ),
+ (
+ Var(_js_expr="df", _var_type=DataFrame).guess_type(),
+ Var(_js_expr="list_var", _var_type=List[int]).guess_type(),
+ ),
+ (
+ Var(_js_expr="df", _var_type=DataFrame).guess_type(),
+ Var(_js_expr="set_var", _var_type=Set[str]).guess_type(),
+ ),
+ (
+ Var(_js_expr="df", _var_type=DataFrame).guess_type(),
+ Var(_js_expr="dict_var", _var_type=Dict[str, str]).guess_type(),
+ ),
+ ],
+)
+def test_var_unsupported_indexing_dicts(var, index):
+ """Test unsupported indexing throws a type error.
+
+ Args:
+ var: The base var.
+ index: The base var index.
+ """
+ with pytest.raises(TypeError):
+ var[index]
+
+
+@pytest.mark.parametrize(
+ "fixture",
+ [
+ "ParentState",
+ "StateWithAnyVar",
+ ],
+)
+def test_computed_var_without_annotation_error(request, fixture):
+ """Test that a type error is thrown when an attribute of a computed var is
+ accessed without annotating the computed var.
+
+ Args:
+ request: Fixture Request.
+ fixture: The state fixture.
+ """
+ with pytest.raises(TypeError) as err:
+ state = request.getfixturevalue(fixture)
+ state.var_without_annotation.foo
+ full_name = state.var_without_annotation._var_full_name
+ assert (
+ err.value.args[0]
+ == f"You must provide an annotation for the state var `{full_name}`. Annotation cannot be `typing.Any`"
+ )
+
+
+@pytest.mark.parametrize(
+ "fixture",
+ [
+ "ChildState",
+ "GrandChildState",
+ ],
+)
+def test_shadow_computed_var_error(request: pytest.FixtureRequest, fixture: str):
+ """Test that a name error is thrown when an attribute of a computed var is
+ shadowed by another attribute.
+
+ Args:
+ request: Fixture Request.
+ fixture: The state fixture.
+ """
+ with pytest.raises(NameError):
+ state = request.getfixturevalue(fixture)
+ state.var_without_annotation.foo
+
+
+@pytest.mark.parametrize(
+ "fixture",
+ [
+ "StateWithCorrectVarAnnotation",
+ "StateWithWrongVarAnnotation",
+ ],
+)
+def test_computed_var_with_annotation_error(request, fixture):
+ """Test that an Attribute error is thrown when a non-existent attribute of an annotated computed var is
+ accessed or when the wrong annotation is provided to a computed var.
+
+ Args:
+ request: Fixture Request.
+ fixture: The state fixture.
+ """
+ with pytest.raises(AttributeError) as err:
+ state = request.getfixturevalue(fixture)
+ state.var_with_annotation.foo
+ full_name = state.var_with_annotation._var_full_name
+ assert (
+ err.value.args[0]
+ == f"The State var `{full_name}` has no attribute 'foo' or may have been annotated wrongly."
+ )
+
+
+@pytest.mark.parametrize(
+ "fixture,var_name,expected_initial,expected_runtime,raises_at_runtime",
+ [
+ (
+ "StateWithInitialComputedVar",
+ "var_with_initial_value",
+ "Initial value",
+ "Runtime value",
+ False,
+ ),
+ (
+ "ChildWithInitialComputedVar",
+ "var_with_initial_value_child",
+ "Initial value",
+ "Runtime value",
+ False,
+ ),
+ (
+ "StateWithRuntimeOnlyVar",
+ "var_raises_at_runtime",
+ None,
+ None,
+ True,
+ ),
+ (
+ "ChildWithRuntimeOnlyVar",
+ "var_raises_at_runtime_child",
+ "Initial value",
+ None,
+ True,
+ ),
+ ],
+)
+def test_state_with_initial_computed_var(
+ request, fixture, var_name, expected_initial, expected_runtime, raises_at_runtime
+):
+ """Test that the initial and runtime values of a computed var are correct.
+
+ Args:
+ request: Fixture Request.
+ fixture: The state fixture.
+ var_name: The name of the computed var.
+ expected_initial: The expected initial value of the computed var.
+ expected_runtime: The expected runtime value of the computed var.
+ raises_at_runtime: Whether the computed var is runtime only.
+ """
+ state = request.getfixturevalue(fixture)()
+ state_name = state.get_full_name()
+ initial_dict = state.dict(initial=True)[state_name]
+ assert initial_dict[var_name] == expected_initial
+
+ if raises_at_runtime:
+ with pytest.raises(ValueError):
+ state.dict()[state_name][var_name]
+ else:
+ runtime_dict = state.dict()[state_name]
+ assert runtime_dict[var_name] == expected_runtime
+
+
+def test_literal_var():
+ complicated_var = LiteralVar.create(
+ [
+ {"a": 1, "b": 2, "c": {"d": 3, "e": 4}},
+ [1, 2, 3, 4],
+ 9,
+ "string",
+ True,
+ False,
+ None,
+ set([1, 2, 3]),
+ ]
+ )
+ assert (
+ str(complicated_var)
+ == '[({ ["a"] : 1, ["b"] : 2, ["c"] : ({ ["d"] : 3, ["e"] : 4 }) }), [1, 2, 3, 4], 9, "string", true, false, null, [1, 2, 3]]'
+ )
+
+
+def test_function_var():
+ addition_func = FunctionStringVar.create("((a, b) => a + b)")
+ assert str(addition_func.call(1, 2)) == "(((a, b) => a + b)(1, 2))"
+
+ manual_addition_func = ArgsFunctionOperation.create(
+ ("a", "b"),
+ {
+ "args": [Var(_js_expr="a"), Var(_js_expr="b")],
+ "result": Var(_js_expr="a + b"),
+ },
+ )
+ assert (
+ str(manual_addition_func.call(1, 2))
+ == '(((a, b) => (({ ["args"] : [a, b], ["result"] : a + b })))(1, 2))'
+ )
+
+ increment_func = addition_func(1)
+ assert (
+ str(increment_func.call(2))
+ == "(((...args) => ((((a, b) => a + b)(1, ...args))))(2))"
+ )
+
+ create_hello_statement = ArgsFunctionOperation.create(
+ ("name",), f"Hello, {Var(_js_expr='name')}!"
+ )
+ first_name = LiteralStringVar.create("Steven")
+ last_name = LiteralStringVar.create("Universe")
+ assert (
+ str(create_hello_statement.call(f"{first_name} {last_name}"))
+ == '(((name) => (("Hello, "+name+"!")))("Steven Universe"))'
+ )
+
+
+def test_var_operation():
+ @var_operation
+ def add(a: Union[NumberVar, int], b: Union[NumberVar, int]):
+ return var_operation_return(js_expression=f"({a} + {b})", var_type=int)
+
+ assert str(add(1, 2)) == "(1 + 2)"
+ assert str(add(a=4, b=-9)) == "(4 + -9)"
+
+ five = LiteralNumberVar.create(5)
+ seven = add(2, five)
+
+ assert isinstance(seven, NumberVar)
+
+
+def test_string_operations():
+ basic_string = LiteralStringVar.create("Hello, World!")
+
+ assert str(basic_string.length()) == '"Hello, World!".split("").length'
+ assert str(basic_string.lower()) == '"Hello, World!".toLowerCase()'
+ assert str(basic_string.upper()) == '"Hello, World!".toUpperCase()'
+ assert str(basic_string.strip()) == '"Hello, World!".trim()'
+ assert str(basic_string.contains("World")) == '"Hello, World!".includes("World")'
+ assert (
+ str(basic_string.split(" ").join(",")) == '"Hello, World!".split(" ").join(",")'
+ )
+
+
+def test_all_number_operations():
+ starting_number = LiteralNumberVar.create(-5.4)
+
+ complicated_number = (((-(starting_number + 1)) * 2 / 3) // 2 % 3) ** 2
+
+ assert (
+ str(complicated_number)
+ == "((Math.floor(((-((-5.4 + 1)) * 2) / 3) / 2) % 3) ** 2)"
+ )
+
+ even_more_complicated_number = ~(
+ abs(math.floor(complicated_number)) | 2 & 3 & round(complicated_number)
+ )
+
+ assert (
+ str(even_more_complicated_number)
+ == "!(((Math.abs(Math.floor(((Math.floor(((-((-5.4 + 1)) * 2) / 3) / 2) % 3) ** 2))) || (2 && Math.round(((Math.floor(((-((-5.4 + 1)) * 2) / 3) / 2) % 3) ** 2)))) !== 0))"
+ )
+
+ assert str(LiteralNumberVar.create(5) > False) == "(5 > 0)"
+ assert str(LiteralBooleanVar.create(False) < 5) == "(Number(false) < 5)"
+ assert (
+ str(LiteralBooleanVar.create(False) < LiteralBooleanVar.create(True))
+ == "(Number(false) < Number(true))"
+ )
+
+
+@pytest.mark.parametrize(
+ ("var", "expected"),
+ [
+ (Var.create(False), "false"),
+ (Var.create(True), "true"),
+ (Var.create("false"), 'isTrue("false")'),
+ (Var.create([1, 2, 3]), "isTrue([1, 2, 3])"),
+ (Var.create({"a": 1, "b": 2}), 'isTrue(({ ["a"] : 1, ["b"] : 2 }))'),
+ (Var("mysterious_var"), "isTrue(mysterious_var)"),
+ ],
+)
+def test_boolify_operations(var, expected):
+ assert str(var.bool()) == expected
+
+
+def test_index_operation():
+ array_var = LiteralArrayVar.create([1, 2, 3, 4, 5])
+ assert str(array_var[0]) == "[1, 2, 3, 4, 5].at(0)"
+ assert str(array_var[1:2]) == "[1, 2, 3, 4, 5].slice(1, 2)"
+ assert (
+ str(array_var[1:4:2])
+ == "[1, 2, 3, 4, 5].slice(1, 4).filter((_, i) => i % 2 === 0)"
+ )
+ assert (
+ str(array_var[::-1])
+ == "[1, 2, 3, 4, 5].slice(0, [1, 2, 3, 4, 5].length).slice().reverse().slice(undefined, undefined).filter((_, i) => i % 1 === 0)"
+ )
+ assert str(array_var.reverse()) == "[1, 2, 3, 4, 5].slice().reverse()"
+ assert str(array_var[0].to(NumberVar) + 9) == "([1, 2, 3, 4, 5].at(0) + 9)"
+
+
+@pytest.mark.parametrize(
+ "var, expected_js",
+ [
+ (Var.create(float("inf")), "Infinity"),
+ (Var.create(-float("inf")), "-Infinity"),
+ (Var.create(float("nan")), "NaN"),
+ ],
+)
+def test_inf_and_nan(var, expected_js):
+ assert str(var) == expected_js
+ assert isinstance(var, NumberVar)
+ assert isinstance(var, LiteralVar)
+ with pytest.raises(PrimitiveUnserializableToJSON):
+ var.json()
+
+
+def test_array_operations():
+ array_var = LiteralArrayVar.create([1, 2, 3, 4, 5])
+
+ assert str(array_var.length()) == "[1, 2, 3, 4, 5].length"
+ assert str(array_var.contains(3)) == "[1, 2, 3, 4, 5].includes(3)"
+ assert str(array_var.reverse()) == "[1, 2, 3, 4, 5].slice().reverse()"
+ assert (
+ str(ArrayVar.range(10))
+ == "Array.from({ length: (10 - 0) / 1 }, (_, i) => 0 + i * 1)"
+ )
+ assert (
+ str(ArrayVar.range(1, 10))
+ == "Array.from({ length: (10 - 1) / 1 }, (_, i) => 1 + i * 1)"
+ )
+ assert (
+ str(ArrayVar.range(1, 10, 2))
+ == "Array.from({ length: (10 - 1) / 2 }, (_, i) => 1 + i * 2)"
+ )
+ assert (
+ str(ArrayVar.range(1, 10, -1))
+ == "Array.from({ length: (10 - 1) / -1 }, (_, i) => 1 + i * -1)"
+ )
+
+
+def test_object_operations():
+ object_var = LiteralObjectVar.create({"a": 1, "b": 2, "c": 3})
+
+ assert (
+ str(object_var.keys()) == 'Object.keys(({ ["a"] : 1, ["b"] : 2, ["c"] : 3 }))'
+ )
+ assert (
+ str(object_var.values())
+ == 'Object.values(({ ["a"] : 1, ["b"] : 2, ["c"] : 3 }))'
+ )
+ assert (
+ str(object_var.entries())
+ == 'Object.entries(({ ["a"] : 1, ["b"] : 2, ["c"] : 3 }))'
+ )
+ assert str(object_var.a) == '({ ["a"] : 1, ["b"] : 2, ["c"] : 3 })["a"]'
+ assert str(object_var["a"]) == '({ ["a"] : 1, ["b"] : 2, ["c"] : 3 })["a"]'
+ assert (
+ str(object_var.merge(LiteralObjectVar.create({"c": 4, "d": 5})))
+ == '({...({ ["a"] : 1, ["b"] : 2, ["c"] : 3 }), ...({ ["c"] : 4, ["d"] : 5 })})'
+ )
+
+
+def test_var_component():
+ class ComponentVarState(rx.State):
+ field_var: rx.Component = rx.text("I am a field var")
+
+ @rx.var
+ def computed_var(self) -> rx.Component:
+ return rx.text("I am a computed var")
+
+ def has_eval_react_component(var: Var):
+ var_data = var._get_all_var_data()
+ assert var_data is not None
+ assert any(
+ any(
+ imported_object.name == "evalReactComponent"
+ for imported_object in imported_objects
+ )
+ for _, imported_objects in var_data.imports
+ )
+
+ has_eval_react_component(ComponentVarState.field_var) # type: ignore
+ has_eval_react_component(ComponentVarState.computed_var)
+
+
+def test_type_chains():
+ object_var = LiteralObjectVar.create({"a": 1, "b": 2, "c": 3})
+ assert (object_var._key_type(), object_var._value_type()) == (str, int)
+ assert (object_var.keys()._var_type, object_var.values()._var_type) == (
+ List[str],
+ List[int],
+ )
+ assert (
+ str(object_var.keys()[0].upper()) # type: ignore
+ == 'Object.keys(({ ["a"] : 1, ["b"] : 2, ["c"] : 3 })).at(0).toUpperCase()'
+ )
+ assert (
+ str(object_var.entries()[1][1] - 1) # type: ignore
+ == '(Object.entries(({ ["a"] : 1, ["b"] : 2, ["c"] : 3 })).at(1).at(1) - 1)'
+ )
+ assert (
+ str(object_var["c"] + object_var["b"]) # type: ignore
+ == '(({ ["a"] : 1, ["b"] : 2, ["c"] : 3 })["c"] + ({ ["a"] : 1, ["b"] : 2, ["c"] : 3 })["b"])'
+ )
+
+
+def test_nested_dict():
+ arr = LiteralArrayVar.create([{"bar": ["foo", "bar"]}], List[Dict[str, List[str]]])
+
+ assert (
+ str(arr[0]["bar"][0]) == '[({ ["bar"] : ["foo", "bar"] })].at(0)["bar"].at(0)'
+ )
+
+
+def nested_base():
+ class Boo(Base):
+ foo: str
+ bar: int
+
+ class Foo(Base):
+ bar: Boo
+ baz: int
+
+ parent_obj = LiteralObjectVar.create(
+ Foo(bar=Boo(foo="bar", bar=5), baz=5).dict(), Foo
+ )
+
+ assert (
+ str(parent_obj.bar.foo)
+ == '({ ["bar"] : ({ ["foo"] : "bar", ["bar"] : 5 }), ["baz"] : 5 })["bar"]["foo"]'
+ )
+
+
+def test_retrival():
+ var_without_data = Var(_js_expr="test")
+ assert var_without_data is not None
+
+ original_var_data = VarData(
+ state="Test",
+ imports={"react": [ImportVar(tag="useRef")]},
+ hooks={"const state = useContext(StateContexts.state)": None},
+ )
+
+ var_with_data = var_without_data._replace(merge_var_data=original_var_data)
+
+ f_string = f"foo{var_with_data}bar"
+
+ assert REFLEX_VAR_OPENING_TAG in f_string
+ assert REFLEX_VAR_CLOSING_TAG in f_string
+
+ result_var_data = LiteralVar.create(f_string)._get_all_var_data()
+ result_immutable_var_data = Var(_js_expr=f_string)._var_data
+ assert result_var_data is not None and result_immutable_var_data is not None
+ assert (
+ result_var_data.state
+ == result_immutable_var_data.state
+ == original_var_data.state
+ )
+ assert (
+ result_var_data.imports
+ == result_immutable_var_data.imports
+ == original_var_data.imports
+ )
+ assert (
+ tuple(result_var_data.hooks)
+ == tuple(result_immutable_var_data.hooks)
+ == tuple(original_var_data.hooks)
+ )
+
+
+def test_fstring_concat():
+ original_var_with_data = LiteralVar.create(
+ "imagination", _var_data=VarData(state="fear")
+ )
+
+ immutable_var_with_data = Var(
+ _js_expr="consequences",
+ _var_data=VarData(
+ imports={
+ "react": [ImportVar(tag="useRef")],
+ "utils": [ImportVar(tag="useEffect")],
+ }
+ ),
+ )
+
+ f_string = f"foo{original_var_with_data}bar{immutable_var_with_data}baz"
+
+ string_concat = LiteralStringVar.create(
+ f_string,
+ _var_data=VarData(
+ hooks={"const state = useContext(StateContexts.state)": None}
+ ),
+ )
+
+ assert str(string_concat) == '("fooimaginationbar"+consequences+"baz")'
+ assert isinstance(string_concat, ConcatVarOperation)
+ assert string_concat._get_all_var_data() == VarData(
+ state="fear",
+ imports={
+ "react": [ImportVar(tag="useRef")],
+ "utils": [ImportVar(tag="useEffect")],
+ },
+ hooks={"const state = useContext(StateContexts.state)": None},
+ )
+
+
+var = Var(_js_expr="var", _var_type=str)
+myvar = Var(_js_expr="myvar", _var_type=int)._var_set_state("state")
+x = Var(_js_expr="x", _var_type=str)
+
+
+@pytest.mark.parametrize(
+ "out, expected",
+ [
+ (f"{var}", f"{hash(var)} var"),
+ (
+ f"testing f-string with {myvar}",
+ f"testing f-string with {hash(myvar)} state.myvar",
+ ),
+ (
+ f"testing local f-string {x}",
+ f"testing local f-string {hash(x)} x",
+ ),
+ ],
+)
+def test_fstrings(out, expected):
+ assert out == expected
+
+
+@pytest.mark.parametrize(
+ ("value", "expect_state"),
+ [
+ ([1], ""),
+ ({"a": 1}, ""),
+ ([LiteralVar.create(1)._var_set_state("foo")], "foo"),
+ ({"a": LiteralVar.create(1)._var_set_state("foo")}, "foo"),
+ ],
+)
+def test_extract_state_from_container(value, expect_state):
+ """Test that _var_state is extracted from containers containing BaseVar.
+
+ Args:
+ value: The value to create a var from.
+ expect_state: The expected state.
+ """
+ var_data = LiteralVar.create(value)._get_all_var_data()
+ var_state = var_data.state if var_data else ""
+ assert var_state == expect_state
+
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ "var",
+ "\nvar",
+ ],
+)
+def test_fstring_roundtrip(value):
+ """Test that f-string roundtrip carries state.
+
+ Args:
+ value: The value to create a Var from.
+ """
+ var = Var(_js_expr=value)._var_set_state("state")
+ rt_var = LiteralVar.create(f"{var}")
+ assert var._var_state == rt_var._var_state
+ assert str(rt_var) == str(var)
+
+
+@pytest.mark.parametrize(
+ "var",
+ [
+ Var(_js_expr="var", _var_type=int).guess_type(),
+ Var(_js_expr="var", _var_type=float).guess_type(),
+ Var(_js_expr="var", _var_type=str).guess_type(),
+ Var(_js_expr="var", _var_type=bool).guess_type(),
+ Var(_js_expr="var", _var_type=dict).guess_type(),
+ Var(_js_expr="var", _var_type=None).guess_type(),
+ ],
+)
+def test_unsupported_types_for_reverse(var):
+ """Test that unsupported types for reverse throw a type error.
+
+ Args:
+ var: The base var.
+ """
+ with pytest.raises(TypeError) as err:
+ var.reverse()
+ assert err.value.args[0] == f"Cannot reverse non-list var."
+
+
+@pytest.mark.parametrize(
+ "var",
+ [
+ Var(_js_expr="var", _var_type=int).guess_type(),
+ Var(_js_expr="var", _var_type=float).guess_type(),
+ Var(_js_expr="var", _var_type=bool).guess_type(),
+ Var(_js_expr="var", _var_type=None).guess_type(),
+ ],
+)
+def test_unsupported_types_for_contains(var):
+ """Test that unsupported types for contains throw a type error.
+
+ Args:
+ var: The base var.
+ """
+ with pytest.raises(TypeError) as err:
+ assert var.contains(1)
+ assert (
+ err.value.args[0]
+ == f"Var of type {var._var_type} does not support contains check."
+ )
+
+
+@pytest.mark.parametrize(
+ "other",
+ [
+ Var(_js_expr="other", _var_type=int).guess_type(),
+ Var(_js_expr="other", _var_type=float).guess_type(),
+ Var(_js_expr="other", _var_type=bool).guess_type(),
+ Var(_js_expr="other", _var_type=list).guess_type(),
+ Var(_js_expr="other", _var_type=dict).guess_type(),
+ Var(_js_expr="other", _var_type=tuple).guess_type(),
+ Var(_js_expr="other", _var_type=set).guess_type(),
+ ],
+)
+def test_unsupported_types_for_string_contains(other):
+ with pytest.raises(TypeError) as err:
+ assert Var(_js_expr="var").to(str).contains(other)
+ assert (
+ err.value.args[0]
+ == f"Unsupported Operand type(s) for contains: ToStringOperation, {type(other).__name__}"
+ )
+
+
+def test_unsupported_default_contains():
+ with pytest.raises(TypeError) as err:
+ assert 1 in Var(_js_expr="var", _var_type=str).guess_type()
+ assert (
+ err.value.args[0]
+ == "'in' operator not supported for Var types, use Var.contains() instead."
+ )
+
+
+@pytest.mark.parametrize(
+ "operand1_var,operand2_var,operators",
+ [
+ (
+ LiteralVar.create(10),
+ LiteralVar.create(5),
+ [
+ "+",
+ "-",
+ "/",
+ "//",
+ "*",
+ "%",
+ "**",
+ ">",
+ "<",
+ "<=",
+ ">=",
+ "|",
+ "&",
+ ],
+ ),
+ (
+ LiteralVar.create(10.5),
+ LiteralVar.create(5),
+ ["+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="],
+ ),
+ (
+ LiteralVar.create(5),
+ LiteralVar.create(True),
+ [
+ "+",
+ "-",
+ "/",
+ "//",
+ "*",
+ "%",
+ "**",
+ ">",
+ "<",
+ "<=",
+ ">=",
+ "|",
+ "&",
+ ],
+ ),
+ (
+ LiteralVar.create(10.5),
+ LiteralVar.create(5.5),
+ ["+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="],
+ ),
+ (
+ LiteralVar.create(10.5),
+ LiteralVar.create(True),
+ ["+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="],
+ ),
+ (LiteralVar.create("10"), LiteralVar.create("5"), ["+", ">", "<", "<=", ">="]),
+ (
+ LiteralVar.create([10, 20]),
+ LiteralVar.create([5, 6]),
+ ["+", ">", "<", "<=", ">="],
+ ),
+ (LiteralVar.create([10, 20]), LiteralVar.create(5), ["*"]),
+ (LiteralVar.create([10, 20]), LiteralVar.create(True), ["*"]),
+ (
+ LiteralVar.create(True),
+ LiteralVar.create(True),
+ [
+ "+",
+ "-",
+ "/",
+ "//",
+ "*",
+ "%",
+ "**",
+ ">",
+ "<",
+ "<=",
+ ">=",
+ "|",
+ "&",
+ ],
+ ),
+ ],
+)
+def test_valid_var_operations(operand1_var: Var, operand2_var, operators: List[str]):
+ """Test that operations do not raise a TypeError.
+
+ Args:
+ operand1_var: left operand.
+ operand2_var: right operand.
+ operators: list of supported operators.
+ """
+ for operator in operators:
+ print(
+ "testing",
+ operator,
+ "on",
+ operand1_var,
+ operand2_var,
+ " of types",
+ type(operand1_var),
+ type(operand2_var),
+ )
+ eval(f"operand1_var {operator} operand2_var")
+ eval(f"operand2_var {operator} operand1_var")
+ # operand1_var.operation(op=operator, other=operand2_var)
+ # operand1_var.operation(op=operator, other=operand2_var, flip=True)
+
+
+@pytest.mark.parametrize(
+ "operand1_var,operand2_var,operators",
+ [
+ (
+ LiteralVar.create(10),
+ LiteralVar.create(5),
+ [
+ "^",
+ "<<",
+ ">>",
+ ],
+ ),
+ (
+ LiteralVar.create(10.5),
+ LiteralVar.create(5),
+ [
+ "^",
+ "<<",
+ ">>",
+ ],
+ ),
+ (
+ LiteralVar.create(10.5),
+ LiteralVar.create(True),
+ [
+ "^",
+ "<<",
+ ">>",
+ ],
+ ),
+ (
+ LiteralVar.create(10.5),
+ LiteralVar.create(5.5),
+ [
+ "^",
+ "<<",
+ ">>",
+ ],
+ ),
+ (
+ LiteralVar.create("10"),
+ LiteralVar.create("5"),
+ [
+ "-",
+ "/",
+ "//",
+ "*",
+ "%",
+ "**",
+ "^",
+ "<<",
+ ">>",
+ ],
+ ),
+ (
+ LiteralVar.create([10, 20]),
+ LiteralVar.create([5, 6]),
+ [
+ "-",
+ "/",
+ "//",
+ "*",
+ "%",
+ "**",
+ "^",
+ "<<",
+ ">>",
+ ],
+ ),
+ (
+ LiteralVar.create([10, 20]),
+ LiteralVar.create(5),
+ [
+ "+",
+ "-",
+ "/",
+ "//",
+ "%",
+ "**",
+ ">",
+ "<",
+ "<=",
+ ">=",
+ "^",
+ "<<",
+ ">>",
+ ],
+ ),
+ (
+ LiteralVar.create([10, 20]),
+ LiteralVar.create(True),
+ [
+ "+",
+ "-",
+ "/",
+ "//",
+ "%",
+ "**",
+ ">",
+ "<",
+ "<=",
+ ">=",
+ "^",
+ "<<",
+ ">>",
+ ],
+ ),
+ (
+ LiteralVar.create([10, 20]),
+ LiteralVar.create("5"),
+ [
+ "+",
+ "-",
+ "/",
+ "//",
+ "*",
+ "%",
+ "**",
+ ">",
+ "<",
+ "<=",
+ ">=",
+ "^",
+ "<<",
+ ">>",
+ ],
+ ),
+ (
+ LiteralVar.create([10, 20]),
+ LiteralVar.create({"key": "value"}),
+ [
+ "+",
+ "-",
+ "/",
+ "//",
+ "*",
+ "%",
+ "**",
+ ">",
+ "<",
+ "<=",
+ ">=",
+ "^",
+ "<<",
+ ">>",
+ ],
+ ),
+ (
+ LiteralVar.create([10, 20]),
+ LiteralVar.create(5.5),
+ [
+ "+",
+ "-",
+ "/",
+ "//",
+ "*",
+ "%",
+ "**",
+ ">",
+ "<",
+ "<=",
+ ">=",
+ "^",
+ "<<",
+ ">>",
+ ],
+ ),
+ (
+ LiteralVar.create({"key": "value"}),
+ LiteralVar.create({"another_key": "another_value"}),
+ [
+ "+",
+ "-",
+ "/",
+ "//",
+ "*",
+ "%",
+ "**",
+ ">",
+ "<",
+ "<=",
+ ">=",
+ "^",
+ "<<",
+ ">>",
+ ],
+ ),
+ (
+ LiteralVar.create({"key": "value"}),
+ LiteralVar.create(5),
+ [
+ "+",
+ "-",
+ "/",
+ "//",
+ "*",
+ "%",
+ "**",
+ ">",
+ "<",
+ "<=",
+ ">=",
+ "^",
+ "<<",
+ ">>",
+ ],
+ ),
+ (
+ LiteralVar.create({"key": "value"}),
+ LiteralVar.create(True),
+ [
+ "+",
+ "-",
+ "/",
+ "//",
+ "*",
+ "%",
+ "**",
+ ">",
+ "<",
+ "<=",
+ ">=",
+ "^",
+ "<<",
+ ">>",
+ ],
+ ),
+ (
+ LiteralVar.create({"key": "value"}),
+ LiteralVar.create(5.5),
+ [
+ "+",
+ "-",
+ "/",
+ "//",
+ "*",
+ "%",
+ "**",
+ ">",
+ "<",
+ "<=",
+ ">=",
+ "^",
+ "<<",
+ ">>",
+ ],
+ ),
+ (
+ LiteralVar.create({"key": "value"}),
+ LiteralVar.create("5"),
+ [
+ "+",
+ "-",
+ "/",
+ "//",
+ "*",
+ "%",
+ "**",
+ ">",
+ "<",
+ "<=",
+ ">=",
+ "^",
+ "<<",
+ ">>",
+ ],
+ ),
+ ],
+)
+def test_invalid_var_operations(operand1_var: Var, operand2_var, operators: List[str]):
+ for operator in operators:
+ print(f"testing {operator} on {str(operand1_var)} and {str(operand2_var)}")
+ with pytest.raises(TypeError):
+ print(eval(f"operand1_var {operator} operand2_var"))
+ # operand1_var.operation(op=operator, other=operand2_var)
+
+ with pytest.raises(TypeError):
+ print(eval(f"operand2_var {operator} operand1_var"))
+ # operand1_var.operation(op=operator, other=operand2_var, flip=True)
+
+
+@pytest.mark.parametrize(
+ "var, expected",
+ [
+ (LiteralVar.create("string_value"), '"string_value"'),
+ (LiteralVar.create(1), "1"),
+ (LiteralVar.create([1, 2, 3]), "[1, 2, 3]"),
+ (LiteralVar.create({"foo": "bar"}), '({ ["foo"] : "bar" })'),
+ (
+ LiteralVar.create(ATestState.value),
+ f"{ATestState.get_full_name()}.value",
+ ),
+ (
+ LiteralVar.create(f"{ATestState.value} string"),
+ f'({ATestState.get_full_name()}.value+" string")',
+ ),
+ (
+ LiteralVar.create(ATestState.dict_val),
+ f"{ATestState.get_full_name()}.dict_val",
+ ),
+ ],
+)
+def test_var_name_unwrapped(var, expected):
+ assert str(var) == expected
+
+
+def cv_fget(state: BaseState) -> int:
+ return 1
+
+
+@pytest.mark.parametrize(
+ "deps,expected",
+ [
+ (["a"], {"a"}),
+ (["b"], {"b"}),
+ ([ComputedVar(fget=cv_fget)], {"cv_fget"}),
+ ],
+)
+def test_computed_var_deps(deps: List[Union[str, Var]], expected: Set[str]):
+ @computed_var(
+ deps=deps,
+ cache=True,
+ )
+ def test_var(state) -> int:
+ return 1
+
+ assert test_var._static_deps == expected
+
+
+@pytest.mark.parametrize(
+ "deps",
+ [
+ [""],
+ [1],
+ ["", "abc"],
+ ],
+)
+def test_invalid_computed_var_deps(deps: List):
+ with pytest.raises(TypeError):
+
+ @computed_var(
+ deps=deps,
+ cache=True,
+ )
+ def test_var(state) -> int:
+ return 1
+
+
+def test_to_string_operation():
+ class Email(str): ...
+
+ class TestState(BaseState):
+ optional_email: Optional[Email] = None
+ email: Email = Email("test@reflex.dev")
+
+ assert (
+ str(TestState.optional_email) == f"{TestState.get_full_name()}.optional_email"
+ )
+ my_state = TestState()
+ assert my_state.optional_email is None
+ assert my_state.email == "test@reflex.dev"
+
+ assert cast(Var, TestState.email)._var_type == Email
+ assert cast(Var, TestState.optional_email)._var_type == Optional[Email]
+
+ single_var = Var.create(Email())
+ assert single_var._var_type == Email
diff --git a/tests/middleware/__init__.py b/tests/units/utils/__init__.py
similarity index 100%
rename from tests/middleware/__init__.py
rename to tests/units/utils/__init__.py
diff --git a/tests/utils/test_format.py b/tests/units/utils/test_format.py
similarity index 66%
rename from tests/utils/test_format.py
rename to tests/units/utils/test_format.py
index 19f385175..f8b605541 100644
--- a/tests/utils/test_format.py
+++ b/tests/units/utils/test_format.py
@@ -1,16 +1,20 @@
from __future__ import annotations
import datetime
+import json
from typing import Any, List
+import plotly.graph_objects as go
import pytest
from reflex.components.tags.tag import Tag
-from reflex.event import EventChain, EventHandler, EventSpec, FrontendEvent
+from reflex.event import EventChain, EventHandler, EventSpec, JavascriptInputEvent
from reflex.style import Style
from reflex.utils import format
-from reflex.vars import BaseVar, Var
-from tests.test_state import (
+from reflex.utils.serializers import serialize_figure
+from reflex.vars.base import LiteralVar, Var
+from reflex.vars.object import ObjectVar
+from tests.units.test_state import (
ChildState,
ChildState2,
ChildState3,
@@ -94,6 +98,36 @@ 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",
[
@@ -240,16 +274,12 @@ def test_format_string(input: str, output: str):
@pytest.mark.parametrize(
"input,output",
[
- (Var.create(value="test"), "{`test`}"),
- (Var.create(value="test", _var_is_local=True), "{`test`}"),
- (Var.create(value="test", _var_is_local=False), "{test}"),
- (Var.create(value="test", _var_is_string=True), "{`test`}"),
- (Var.create(value="test", _var_is_string=False), "{`test`}"),
- (Var.create(value="test", _var_is_local=False, _var_is_string=False), "{test}"),
+ (LiteralVar.create(value="test"), '"test"'),
+ (Var(_js_expr="test"), "test"),
],
)
def test_format_var(input: Var, output: str):
- assert format.format_var(input) == output
+ assert str(input) == output
@pytest.mark.parametrize(
@@ -280,134 +310,33 @@ 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,true_value,false_value,is_prop,expected",
- [
- ("cond", "", '""', False, '{isTrue(cond) ? : ""}'),
- ("cond", "", "", False, "{isTrue(cond) ? : }"),
- (
- "cond",
- Var.create_safe(""),
- "",
- False,
- "{isTrue(cond) ? : }",
- ),
- (
- "cond",
- Var.create_safe(""),
- Var.create_safe(""),
- False,
- "{isTrue(cond) ? : }",
- ),
- (
- "cond",
- Var.create_safe("", _var_is_local=False),
- Var.create_safe(""),
- False,
- "{isTrue(cond) ? ${} : }",
- ),
- (
- "cond",
- Var.create_safe("", _var_is_string=True),
- Var.create_safe(""),
- False,
- "{isTrue(cond) ? {``} : }",
- ),
- ("cond", "", '""', True, 'isTrue(cond) ? `` : `""`'),
- ("cond", "", "", True, "isTrue(cond) ? `` : ``"),
- (
- "cond",
- Var.create_safe(""),
- "",
- True,
- "isTrue(cond) ? : ``",
- ),
- (
- "cond",
- Var.create_safe(""),
- Var.create_safe(""),
- True,
- "isTrue(cond) ? : ",
- ),
- (
- "cond",
- Var.create_safe("", _var_is_local=False),
- Var.create_safe(""),
- True,
- "isTrue(cond) ? : ",
- ),
- (
- "cond",
- Var.create_safe(""),
- Var.create_safe("", _var_is_local=False),
- True,
- "isTrue(cond) ? : ",
- ),
- (
- "cond",
- Var.create_safe("", _var_is_string=True),
- Var.create_safe(""),
- True,
- "isTrue(cond) ? `` : ",
- ),
- ],
-)
-def test_format_cond(
- condition: str,
- true_value: str | Var,
- false_value: str | Var,
- is_prop: bool,
- expected: str,
-):
- """Test formatting a cond.
-
- Args:
- condition: The condition to check.
- true_value: The value to return if the condition is true.
- false_value: The value to return if the condition is false.
- is_prop: Whether the values are rendered as props or not.
- expected: The expected output string.
- """
- orig_true_value = (
- true_value._replace() if isinstance(true_value, Var) else Var.create_safe("")
- )
- orig_false_value = (
- false_value._replace() if isinstance(false_value, Var) else Var.create_safe("")
- )
-
- assert format.format_cond(condition, true_value, false_value, is_prop) == expected
-
- # Ensure the formatting operation didn't change the original Var
- if isinstance(true_value, Var):
- assert true_value.equals(orig_true_value)
- if isinstance(false_value, Var):
- assert false_value.equals(orig_false_value)
-
-
@pytest.mark.parametrize(
"condition, match_cases, default,expected",
[
(
"state__state.value",
[
- [Var.create(1), Var.create("red", _var_is_string=True)],
- [Var.create(2), Var.create(3), Var.create("blue", _var_is_string=True)],
+ [LiteralVar.create(1), LiteralVar.create("red")],
+ [LiteralVar.create(2), LiteralVar.create(3), LiteralVar.create("blue")],
[TestState.mapping, TestState.num1],
[
- Var.create(f"{TestState.map_key}-key", _var_is_string=True),
- Var.create("return-key", _var_is_string=True),
+ LiteralVar.create(f"{TestState.map_key}-key"),
+ LiteralVar.create("return-key"),
],
],
- Var.create("yellow", _var_is_string=True),
- "(() => { switch (JSON.stringify(state__state.value)) {case JSON.stringify(1): return (`red`); break;case JSON.stringify(2): case JSON.stringify(3): "
- "return (`blue`); break;case JSON.stringify(test_state.mapping): return "
- "(test_state.num1); break;case JSON.stringify(`${test_state.map_key}-key`): return (`return-key`);"
- " break;default: return (`yellow`); break;};})()",
+ 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[BaseVar], default: BaseVar, expected: str
+ condition: str,
+ match_cases: List[List[Var]],
+ default: Var,
+ expected: str,
):
"""Test formatting a match statement.
@@ -424,28 +353,28 @@ def test_format_match(
"prop,formatted",
[
("string", '"string"'),
- ("{wrapped_string}", "{wrapped_string}"),
- (True, "{true}"),
- (False, "{false}"),
- (123, "{123}"),
- (3.14, "{3.14}"),
- ([1, 2, 3], "{[1, 2, 3]}"),
- (["a", "b", "c"], '{["a", "b", "c"]}'),
- ({"a": 1, "b": 2, "c": 3}, '{{"a": 1, "b": 2, "c": 3}}'),
- ({"a": 'foo "bar" baz'}, r'{{"a": "foo \"bar\" baz"}}'),
+ ("{wrapped_string}", '"{wrapped_string}"'),
+ (True, "true"),
+ (False, "false"),
+ (123, "123"),
+ (3.14, "3.14"),
+ ([1, 2, 3], "[1, 2, 3]"),
+ (["a", "b", "c"], '["a", "b", "c"]'),
+ ({"a": 1, "b": 2, "c": 3}, '({ ["a"] : 1, ["b"] : 2, ["c"] : 3 })'),
+ ({"a": 'foo "bar" baz'}, r'({ ["a"] : "foo \"bar\" baz" })'),
(
{
"a": 'foo "{ "bar" }" baz',
- "b": BaseVar(_var_name="val", _var_type="str"),
+ "b": Var(_js_expr="val", _var_type=str).guess_type(),
},
- r'{{"a": "foo \"{ \"bar\" }\" baz", "b": val}}',
+ r'({ ["a"] : "foo \"{ \"bar\" }\" baz", ["b"] : val })',
),
(
EventChain(
events=[EventSpec(handler=EventHandler(fn=mock_event))],
args_spec=lambda: [],
),
- '{(_e) => addEvents([Event("mock_event", {})], (_e), {})}',
+ '((...args) => ((addEvents([(Event("mock_event", ({ }), ({ })))], args, ({ })))))',
),
(
EventChain(
@@ -454,18 +383,19 @@ def test_format_match(
handler=EventHandler(fn=mock_event),
args=(
(
- Var.create_safe("arg"),
- BaseVar(
- _var_name="_e",
- _var_type=FrontendEvent,
- ).target.value,
+ Var(_js_expr="arg"),
+ Var(
+ _js_expr="_e",
+ )
+ .to(ObjectVar, JavascriptInputEvent)
+ .target.value,
),
),
)
],
- args_spec=lambda: [],
+ args_spec=lambda e: [e.target.value],
),
- '{(_e) => addEvents([Event("mock_event", {arg:_e.target.value})], (_e), {})}',
+ '((_e) => ((addEvents([(Event("mock_event", ({ ["arg"] : _e["target"]["value"] }), ({ })))], [_e], ({ })))))',
),
(
EventChain(
@@ -473,7 +403,19 @@ def test_format_match(
args_spec=lambda: [],
event_actions={"stopPropagation": True},
),
- '{(_e) => addEvents([Event("mock_event", {})], (_e), {"stopPropagation": true})}',
+ '((...args) => ((addEvents([(Event("mock_event", ({ }), ({ })))], args, ({ ["stopPropagation"] : true })))))',
+ ),
+ (
+ EventChain(
+ events=[
+ EventSpec(
+ handler=EventHandler(fn=mock_event),
+ event_actions={"stopPropagation": True},
+ )
+ ],
+ args_spec=lambda: [],
+ ),
+ '((...args) => ((addEvents([(Event("mock_event", ({ }), ({ ["stopPropagation"] : true })))], args, ({ })))))',
),
(
EventChain(
@@ -481,35 +423,41 @@ def test_format_match(
args_spec=lambda: [],
event_actions={"preventDefault": True},
),
- '{(_e) => addEvents([Event("mock_event", {})], (_e), {"preventDefault": true})}',
+ '((...args) => ((addEvents([(Event("mock_event", ({ }), ({ })))], args, ({ ["preventDefault"] : true })))))',
),
- ({"a": "red", "b": "blue"}, '{{"a": "red", "b": "blue"}}'),
- (BaseVar(_var_name="var", _var_type="int"), "{var}"),
+ ({"a": "red", "b": "blue"}, '({ ["a"] : "red", ["b"] : "blue" })'),
+ (Var(_js_expr="var", _var_type=int).guess_type(), "var"),
(
- BaseVar(
- _var_name="_",
+ Var(
+ _js_expr="_",
_var_type=Any,
- _var_is_local=True,
- _var_is_string=False,
),
- "{_}",
+ "_",
),
(
- BaseVar(_var_name='state.colors["a"]', _var_type="str"),
- '{state.colors["a"]}',
+ Var(_js_expr='state.colors["a"]', _var_type=str).guess_type(),
+ 'state.colors["a"]',
),
- ({"a": BaseVar(_var_name="val", _var_type="str")}, '{{"a": val}}'),
- ({"a": BaseVar(_var_name='"val"', _var_type="str")}, '{{"a": "val"}}'),
(
- {"a": BaseVar(_var_name='state.colors["val"]', _var_type="str")},
- '{{"a": state.colors["val"]}}',
+ {"a": Var(_js_expr="val", _var_type=str).guess_type()},
+ '({ ["a"] : val })',
+ ),
+ (
+ {"a": Var(_js_expr='"val"', _var_type=str).guess_type()},
+ '({ ["a"] : "val" })',
+ ),
+ (
+ {"a": Var(_js_expr='state.colors["val"]', _var_type=str).guess_type()},
+ '({ ["a"] : state.colors["val"] })',
),
# tricky real-world case from markdown component
(
{
- "h1": f"{{({{node, ...props}}) => }}"
+ "h1": Var(
+ _js_expr=f"(({{node, ...props}}) => )"
+ ),
},
- '{{"h1": ({node, ...props}) => }}',
+ '({ ["h1"] : (({node, ...props}) => ) })',
),
],
)
@@ -520,13 +468,17 @@ def test_format_prop(prop: Var, formatted: str):
prop: The prop to test.
formatted: The expected formatted value.
"""
- assert format.format_prop(prop) == formatted
+ assert format.format_prop(LiteralVar.create(prop)) == formatted
@pytest.mark.parametrize(
"single_props,key_value_props,output",
[
- (["string"], {"key": 42}, ["key={42}", "string"]),
+ (
+ [Var(_js_expr="{...props}")],
+ {"key": 42},
+ ["key={42}", "{...props}"],
+ ),
],
)
def test_format_props(single_props, key_value_props, output):
@@ -553,11 +505,14 @@ def test_get_handler_parts(input, output):
@pytest.mark.parametrize(
"input,output",
[
- (TestState.do_something, "test_state.do_something"),
- (ChildState.change_both, "test_state.child_state.change_both"),
+ (TestState.do_something, f"{TestState.get_full_name()}.do_something"),
+ (
+ ChildState.change_both,
+ f"{ChildState.get_full_name()}.change_both",
+ ),
(
GrandchildState.do_nothing,
- "test_state.child_state.grandchild_state.do_nothing",
+ f"{GrandchildState.get_full_name()}.do_nothing",
),
],
)
@@ -574,40 +529,14 @@ def test_format_event_handler(input, output):
@pytest.mark.parametrize(
"input,output",
[
- (EventSpec(handler=EventHandler(fn=mock_event)), 'Event("mock_event", {})'),
+ (
+ EventSpec(handler=EventHandler(fn=mock_event)),
+ '(Event("mock_event", ({ }), ({ })))',
+ ),
],
)
def test_format_event(input, output):
- assert format.format_event(input) == output
-
-
-@pytest.mark.parametrize(
- "input,output",
- [
- (
- EventChain(
- events=[
- EventSpec(handler=EventHandler(fn=mock_event)),
- EventSpec(handler=EventHandler(fn=mock_event)),
- ],
- args_spec=None,
- ),
- 'addEvents([Event("mock_event", {}),Event("mock_event", {})])',
- ),
- (
- EventChain(
- events=[
- EventSpec(handler=EventHandler(fn=mock_event)),
- EventSpec(handler=EventHandler(fn=mock_event)),
- ],
- args_spec=lambda e0: [e0],
- ),
- 'addEvents([Event("mock_event", {}),Event("mock_event", {})])',
- ),
- ],
-)
-def test_format_event_chain(input, output):
- assert format.format_event_chain(input) == output
+ assert str(LiteralVar.create(input)) == output
@pytest.mark.parametrize(
@@ -628,6 +557,7 @@ formatted_router = {
"origin": "",
"upgrade": "",
"connection": "",
+ "cookie": "",
"pragma": "",
"cache_control": "",
"user_agent": "",
@@ -661,7 +591,7 @@ formatted_router = {
2: {"prop1": 42, "prop2": "hello"},
},
"dt": "1989-11-09 18:53:00+01:00",
- "fig": [],
+ "fig": serialize_figure(go.Figure()),
"key": "",
"map_key": "a",
"mapping": {"a": [1, 2, 3], "b": [4, 5, 6]},
@@ -671,6 +601,7 @@ formatted_router = {
"sum": 3.14,
"upper": "",
"router": formatted_router,
+ "asynctest": 0,
},
ChildState.get_full_name(): {
"count": 23,
@@ -704,7 +635,7 @@ def test_format_state(input, output):
input: The state to format.
output: The expected formatted state.
"""
- assert format.format_state(input) == output
+ assert json.loads(format.json_dumps(input)) == json.loads(format.json_dumps(output))
@pytest.mark.parametrize(
@@ -731,29 +662,14 @@ def test_format_ref(input, output):
"input,output",
[
(("my_array", None), "refs_my_array"),
- (("my_array", Var.create(0)), "refs_my_array[0]"),
- (("my_array", Var.create(1)), "refs_my_array[1]"),
+ (("my_array", LiteralVar.create(0)), "refs_my_array[0]"),
+ (("my_array", LiteralVar.create(1)), "refs_my_array[1]"),
],
)
def test_format_array_ref(input, output):
assert format.format_array_ref(input[0], input[1]) == output
-@pytest.mark.parametrize(
- "input,output",
- [
- ("/foo", [("foo", "/foo")]),
- ("/foo/bar", [("foo", "/foo"), ("bar", "/foo/bar")]),
- (
- "/foo/bar/baz",
- [("foo", "/foo"), ("bar", "/foo/bar"), ("baz", "/foo/bar/baz")],
- ),
- ],
-)
-def test_format_breadcrumbs(input, output):
- assert format.format_breadcrumbs(input) == output
-
-
@pytest.mark.parametrize(
"input, output",
[
diff --git a/tests/utils/test_imports.py b/tests/units/utils/test_imports.py
similarity index 57%
rename from tests/utils/test_imports.py
rename to tests/units/utils/test_imports.py
index c7253ff6b..c30d1d85c 100644
--- a/tests/utils/test_imports.py
+++ b/tests/units/utils/test_imports.py
@@ -1,6 +1,12 @@
import pytest
-from reflex.utils.imports import ImportVar, merge_imports
+from reflex.utils.imports import (
+ ImportDict,
+ ImportVar,
+ ParsedImportDict,
+ merge_imports,
+ parse_imports,
+)
@pytest.mark.parametrize(
@@ -48,17 +54,21 @@ def test_import_var(import_var, expected_name):
(
{"react": {"Component"}},
{"react": {"Component"}, "react-dom": {"render"}},
- {"react": {"Component"}, "react-dom": {"render"}},
+ {"react": {ImportVar("Component")}, "react-dom": {ImportVar("render")}},
),
(
{"react": {"Component"}, "next/image": {"Image"}},
{"react": {"Component"}, "react-dom": {"render"}},
- {"react": {"Component"}, "react-dom": {"render"}, "next/image": {"Image"}},
+ {
+ "react": {ImportVar("Component")},
+ "react-dom": {ImportVar("render")},
+ "next/image": {ImportVar("Image")},
+ },
),
(
{"react": {"Component"}},
{"": {"some/custom.css"}},
- {"react": {"Component"}, "": {"some/custom.css"}},
+ {"react": {ImportVar("Component")}, "": {ImportVar("some/custom.css")}},
),
],
)
@@ -72,7 +82,36 @@ def test_merge_imports(input_1, input_2, output):
"""
res = merge_imports(input_1, input_2)
- assert set(res.keys()) == set(output.keys())
+ assert res.keys() == output.keys()
for key in output:
assert set(res[key]) == set(output[key])
+
+
+@pytest.mark.parametrize(
+ "input, output",
+ [
+ ({}, {}),
+ (
+ {"react": "Component"},
+ {"react": [ImportVar(tag="Component")]},
+ ),
+ (
+ {"react": ["Component"]},
+ {"react": [ImportVar(tag="Component")]},
+ ),
+ (
+ {"react": ["Component", ImportVar(tag="useState")]},
+ {"react": [ImportVar(tag="Component"), ImportVar(tag="useState")]},
+ ),
+ (
+ {"react": ["Component"], "foo": "anotherFunction"},
+ {
+ "react": [ImportVar(tag="Component")],
+ "foo": [ImportVar(tag="anotherFunction")],
+ },
+ ),
+ ],
+)
+def test_parse_imports(input: ImportDict, output: ParsedImportDict):
+ assert parse_imports(input) == output
diff --git a/tests/utils/test_serializers.py b/tests/units/utils/test_serializers.py
similarity index 57%
rename from tests/utils/test_serializers.py
rename to tests/units/utils/test_serializers.py
index 62834d3cc..8050470c6 100644
--- a/tests/utils/test_serializers.py
+++ b/tests/units/utils/test_serializers.py
@@ -1,18 +1,21 @@
import datetime
+import json
from enum import Enum
-from typing import Any, Dict, List, Type
+from pathlib import Path
+from typing import Any, Type
import pytest
from reflex.base import Base
from reflex.components.core.colors import Color
from reflex.utils import serializers
-from reflex.vars import Var
+from reflex.utils.format import json_dumps
+from reflex.vars.base import LiteralVar
@pytest.mark.parametrize(
"type_,expected",
- [(str, True), (dict, True), (Dict[int, int], True), (Enum, True)],
+ [(Enum, True)],
)
def test_has_serializer(type_: Type, expected: bool):
"""Test that has_serializer returns the correct value.
@@ -28,20 +31,10 @@ def test_has_serializer(type_: Type, expected: bool):
@pytest.mark.parametrize(
"type_,expected",
[
- (str, serializers.serialize_str),
- (list, serializers.serialize_list),
- (tuple, serializers.serialize_list),
- (set, serializers.serialize_list),
- (dict, serializers.serialize_dict),
- (List[str], serializers.serialize_list),
- (Dict[int, int], serializers.serialize_dict),
(datetime.datetime, serializers.serialize_datetime),
(datetime.date, serializers.serialize_datetime),
(datetime.time, serializers.serialize_datetime),
(datetime.timedelta, serializers.serialize_datetime),
- (int, serializers.serialize_primitive),
- (float, serializers.serialize_primitive),
- (bool, serializers.serialize_primitive),
(Enum, serializers.serialize_enum),
],
)
@@ -90,6 +83,9 @@ def test_add_serializer():
# Remove the serializer.
serializers.SERIALIZERS.pop(Foo)
+ # LRU cache will still have the serializer, so we need to clear it.
+ assert serializers.has_serializer(Foo)
+ serializers.get_serializer.cache_clear()
assert not serializers.has_serializer(Foo)
@@ -100,7 +96,7 @@ class StrEnum(str, Enum):
BAR = "bar"
-class TestEnum(Enum):
+class FooBarEnum(Enum):
"""A lone enum class."""
FOO = "foo"
@@ -129,48 +125,59 @@ class BaseSubclass(Base):
"value,expected",
[
("test", "test"),
- (1, "1"),
- (1.0, "1.0"),
- (True, "true"),
- (False, "false"),
- (None, "null"),
- ([1, 2, 3], "[1, 2, 3]"),
- ([1, "2", 3.0], '[1, "2", 3.0]'),
- ([{"key": 1}, {"key": 2}], '[{"key": 1}, {"key": 2}]'),
+ (1, 1),
+ (1.0, 1.0),
+ (True, True),
+ (False, False),
+ (None, None),
+ ([1, 2, 3], [1, 2, 3]),
+ ([1, "2", 3.0], [1, "2", 3.0]),
+ ([{"key": 1}, {"key": 2}], [{"key": 1}, {"key": 2}]),
(StrEnum.FOO, "foo"),
- ([StrEnum.FOO, StrEnum.BAR], '["foo", "bar"]'),
+ ([StrEnum.FOO, StrEnum.BAR], ["foo", "bar"]),
(
{"key1": [1, 2, 3], "key2": [StrEnum.FOO, StrEnum.BAR]},
- '{"key1": [1, 2, 3], "key2": ["foo", "bar"]}',
+ {
+ "key1": [1, 2, 3],
+ "key2": ["foo", "bar"],
+ },
),
(EnumWithPrefix.FOO, "prefix_foo"),
- ([EnumWithPrefix.FOO, EnumWithPrefix.BAR], '["prefix_foo", "prefix_bar"]'),
+ ([EnumWithPrefix.FOO, EnumWithPrefix.BAR], ["prefix_foo", "prefix_bar"]),
(
{"key1": EnumWithPrefix.FOO, "key2": EnumWithPrefix.BAR},
- '{"key1": "prefix_foo", "key2": "prefix_bar"}',
+ {
+ "key1": "prefix_foo",
+ "key2": "prefix_bar",
+ },
),
- (TestEnum.FOO, "foo"),
- ([TestEnum.FOO, TestEnum.BAR], '["foo", "bar"]'),
+ (FooBarEnum.FOO, "foo"),
+ ([FooBarEnum.FOO, FooBarEnum.BAR], ["foo", "bar"]),
(
- {"key1": TestEnum.FOO, "key2": TestEnum.BAR},
- '{"key1": "foo", "key2": "bar"}',
+ {"key1": FooBarEnum.FOO, "key2": FooBarEnum.BAR},
+ {
+ "key1": "foo",
+ "key2": "bar",
+ },
),
(
BaseSubclass(ts=datetime.timedelta(1, 1, 1)),
- '{"ts": "1 day, 0:00:01.000001"}',
+ {
+ "ts": "1 day, 0:00:01.000001",
+ },
),
(
- [1, Var.create_safe("hi"), Var.create_safe("bye", _var_is_local=False)],
- '[1, "hi", bye]',
+ [1, LiteralVar.create("hi")],
+ [1, "hi"],
),
(
- (1, Var.create_safe("hi"), Var.create_safe("bye", _var_is_local=False)),
- '[1, "hi", bye]',
+ (1, LiteralVar.create("hi")),
+ [1, "hi"],
),
- ({1: 2, 3: 4}, '{"1": 2, "3": 4}'),
+ ({1: 2, 3: 4}, {1: 2, 3: 4}),
(
- {1: Var.create_safe("hi"), 3: Var.create_safe("bye", _var_is_local=False)},
- '{"1": "hi", "3": bye}',
+ {1: LiteralVar.create("hi")},
+ {1: "hi"},
),
(datetime.datetime(2021, 1, 1, 1, 1, 1, 1), "2021-01-01 01:01:01.000001"),
(datetime.date(2021, 1, 1), "2021-01-01"),
@@ -178,7 +185,7 @@ class BaseSubclass(Base):
(datetime.timedelta(1, 1, 1), "1 day, 0:00:01.000001"),
(
[datetime.timedelta(1, 1, 1), datetime.timedelta(1, 1, 2)],
- '["1 day, 0:00:01.000001", "1 day, 0:00:01.000002"]',
+ ["1 day, 0:00:01.000001", "1 day, 0:00:01.000002"],
),
(Color(color="slate", shade=1), "var(--slate-1)"),
(Color(color="orange", shade=1, alpha=True), "var(--orange-a1)"),
@@ -193,4 +200,43 @@ def test_serialize(value: Any, expected: str):
value: The value to serialize.
expected: The expected result.
"""
- assert serializers.serialize(value) == expected
+ assert json.loads(json_dumps(value)) == json.loads(json_dumps(expected))
+
+
+@pytest.mark.parametrize(
+ "value,expected,exp_var_is_string",
+ [
+ ("test", '"test"', False),
+ (1, "1", False),
+ (1.0, "1.0", False),
+ (True, "true", False),
+ (False, "false", False),
+ ([1, 2, 3], "[1, 2, 3]", False),
+ ([{"key": 1}, {"key": 2}], '[({ ["key"] : 1 }), ({ ["key"] : 2 })]', False),
+ (StrEnum.FOO, '"foo"', False),
+ ([StrEnum.FOO, StrEnum.BAR], '["foo", "bar"]', False),
+ (
+ BaseSubclass(ts=datetime.timedelta(1, 1, 1)),
+ '({ ["ts"] : "1 day, 0:00:01.000001" })',
+ False,
+ ),
+ (
+ datetime.datetime(2021, 1, 1, 1, 1, 1, 1),
+ '"2021-01-01 01:01:01.000001"',
+ True,
+ ),
+ (Color(color="slate", shade=1), '"var(--slate-1)"', True),
+ (BaseSubclass, '"BaseSubclass"', True),
+ (Path("."), '"."', True),
+ ],
+)
+def test_serialize_var_to_str(value: Any, expected: str, exp_var_is_string: bool):
+ """Test that serialize with `to=str` passed to a Var is marked with _var_is_string.
+
+ Args:
+ value: The value to serialize.
+ expected: The expected result.
+ exp_var_is_string: The expected value of _var_is_string.
+ """
+ v = LiteralVar.create(value)
+ assert str(v) == expected
diff --git a/tests/utils/test_types.py b/tests/units/utils/test_types.py
similarity index 60%
rename from tests/utils/test_types.py
rename to tests/units/utils/test_types.py
index fc9261e04..623aacc1f 100644
--- a/tests/utils/test_types.py
+++ b/tests/units/utils/test_types.py
@@ -1,4 +1,4 @@
-from typing import Any, List, Literal, Tuple, Union
+from typing import Any, Dict, List, Literal, Tuple, Union
import pytest
@@ -45,3 +45,48 @@ def test_issubclass(
cls: types.GenericType, cls_check: types.GenericType, expected: bool
) -> None:
assert types._issubclass(cls, cls_check) == expected
+
+
+class CustomDict(dict[str, str]):
+ """A custom dict with generic arguments."""
+
+ pass
+
+
+class ChildCustomDict(CustomDict):
+ """A child of CustomDict."""
+
+ pass
+
+
+class GenericDict(dict):
+ """A generic dict with no generic arguments."""
+
+ pass
+
+
+class ChildGenericDict(GenericDict):
+ """A child of GenericDict."""
+
+ pass
+
+
+@pytest.mark.parametrize(
+ "cls,expected",
+ [
+ (int, False),
+ (str, False),
+ (float, False),
+ (Tuple[int], True),
+ (List[int], True),
+ (Union[int, str], True),
+ (Union[str, int], True),
+ (Dict[str, int], True),
+ (CustomDict, True),
+ (ChildCustomDict, True),
+ (GenericDict, False),
+ (ChildGenericDict, False),
+ ],
+)
+def test_has_args(cls, expected: bool) -> None:
+ assert types.has_args(cls) == expected
diff --git a/tests/utils/test_utils.py b/tests/units/utils/test_utils.py
similarity index 83%
rename from tests/utils/test_utils.py
rename to tests/units/utils/test_utils.py
index 79dda0a70..dd88138bf 100644
--- a/tests/utils/test_utils.py
+++ b/tests/units/utils/test_utils.py
@@ -1,7 +1,8 @@
import os
import typing
+from functools import cached_property
from pathlib import Path
-from typing import Any, List, Literal, Union
+from typing import Any, ClassVar, Dict, List, Literal, Type, Union
import pytest
import typer
@@ -17,8 +18,8 @@ from reflex.utils import (
types,
)
from reflex.utils import exec as utils_exec
-from reflex.utils.serializers import serialize
-from reflex.vars import Var
+from reflex.utils.exceptions import ReflexError
+from reflex.vars.base import Var
def mock_event(arg):
@@ -76,6 +77,47 @@ def test_is_generic_alias(cls: type, expected: bool):
assert types.is_generic_alias(cls) == expected
+@pytest.mark.parametrize(
+ ("subclass", "superclass", "expected"),
+ [
+ *[
+ (base_type, base_type, True)
+ for base_type in [int, float, str, bool, list, dict]
+ ],
+ *[
+ (one_type, another_type, False)
+ for one_type in [int, float, str, list, dict]
+ for another_type in [int, float, str, list, dict]
+ if one_type != another_type
+ ],
+ (bool, int, True),
+ (int, bool, False),
+ (list, List, True),
+ (list, List[str], True), # this is wrong, but it's a limitation of the function
+ (List, list, True),
+ (List[int], list, True),
+ (List[int], List, True),
+ (List[int], List[str], False),
+ (List[int], List[int], True),
+ (List[int], List[float], False),
+ (List[int], List[Union[int, float]], True),
+ (List[int], List[Union[float, str]], False),
+ (Union[int, float], List[Union[int, float]], False),
+ (Union[int, float], Union[int, float, str], True),
+ (Union[int, float], Union[str, float], False),
+ (Dict[str, int], Dict[str, int], True),
+ (Dict[str, bool], Dict[str, int], True),
+ (Dict[str, int], Dict[str, bool], False),
+ (Dict[str, Any], dict[str, str], False),
+ (Dict[str, str], dict[str, str], True),
+ (Dict[str, str], dict[str, Any], True),
+ (Dict[str, Any], dict[str, Any], True),
+ ],
+)
+def test_typehint_issubclass(subclass, superclass, expected):
+ assert types.typehint_issubclass(subclass, superclass) == expected
+
+
def test_validate_invalid_bun_path(mocker):
"""Test that an error is thrown when a custom specified bun path is not valid
or does not exist.
@@ -116,7 +158,7 @@ def test_remove_existing_bun_installation(mocker):
Args:
mocker: Pytest mocker.
"""
- mocker.patch("reflex.utils.prerequisites.os.path.exists", return_value=True)
+ mocker.patch("reflex.utils.prerequisites.Path.exists", return_value=True)
rm = mocker.patch("reflex.utils.prerequisites.path_ops.rm", mocker.Mock())
prerequisites.remove_existing_bun_installation()
@@ -146,26 +188,49 @@ def test_setup_frontend(tmp_path, mocker):
@pytest.fixture
def test_backend_variable_cls():
- class TestBackendVariable:
+ class TestBackendVariable(BaseState):
"""Test backend variable."""
+ _classvar: ClassVar[int] = 0
_hidden: int = 0
not_hidden: int = 0
__dunderattr__: int = 0
+ @classmethod
+ def _class_method(cls):
+ pass
+
+ def _hidden_method(self):
+ pass
+
+ @property
+ def _hidden_property(self):
+ pass
+
+ @cached_property
+ def _cached_hidden_property(self):
+ pass
+
return TestBackendVariable
@pytest.mark.parametrize(
"input, output",
[
+ ("_classvar", False),
+ ("_class_method", False),
+ ("_hidden_method", False),
("_hidden", True),
("not_hidden", False),
("__dundermethod__", False),
+ ("_hidden_property", False),
+ ("_cached_hidden_property", False),
],
)
-def test_is_backend_variable(test_backend_variable_cls, input, output):
- assert types.is_backend_variable(input, test_backend_variable_cls) == output
+def test_is_backend_base_variable(
+ test_backend_variable_cls: Type[BaseState], input: str, output: bool
+):
+ assert types.is_backend_base_variable(input, test_backend_variable_cls) == output
@pytest.mark.parametrize(
@@ -434,7 +499,7 @@ def test_bun_install_without_unzip(mocker):
mocker: Pytest mocker object.
"""
mocker.patch("reflex.utils.path_ops.which", return_value=None)
- mocker.patch("os.path.exists", return_value=False)
+ mocker.patch("pathlib.Path.exists", return_value=False)
mocker.patch("reflex.utils.prerequisites.constants.IS_WINDOWS", False)
with pytest.raises(FileNotFoundError):
@@ -452,7 +517,7 @@ def test_bun_install_version(mocker, bun_version):
"""
mocker.patch("reflex.utils.prerequisites.constants.IS_WINDOWS", False)
- mocker.patch("os.path.exists", return_value=True)
+ mocker.patch("pathlib.Path.exists", return_value=True)
mocker.patch(
"reflex.utils.prerequisites.get_bun_version",
return_value=version.parse(bun_version),
@@ -514,11 +579,17 @@ def test_style_prop_with_event_handler_value(callable):
callable: The callable function or event handler.
"""
+ import reflex as rx
+
style = {
"color": (
- EventHandler(fn=callable) if type(callable) != EventHandler else callable
+ EventHandler(fn=callable)
+ if type(callable) is not EventHandler
+ else callable
)
}
- with pytest.raises(TypeError):
- serialize(style) # type: ignore
+ with pytest.raises(ReflexError):
+ rx.box(
+ style=style, # type: ignore
+ )
diff --git a/tests/units/vars/test_base.py b/tests/units/vars/test_base.py
new file mode 100644
index 000000000..68bc0c38e
--- /dev/null
+++ b/tests/units/vars/test_base.py
@@ -0,0 +1,49 @@
+from typing import Dict, List, Union
+
+import pytest
+
+from reflex.vars.base import figure_out_type
+
+
+class CustomDict(dict[str, str]):
+ """A custom dict with generic arguments."""
+
+ pass
+
+
+class ChildCustomDict(CustomDict):
+ """A child of CustomDict."""
+
+ pass
+
+
+class GenericDict(dict):
+ """A generic dict with no generic arguments."""
+
+ pass
+
+
+class ChildGenericDict(GenericDict):
+ """A child of GenericDict."""
+
+ pass
+
+
+@pytest.mark.parametrize(
+ ("value", "expected"),
+ [
+ (1, int),
+ (1.0, float),
+ ("a", str),
+ ([1, 2, 3], List[int]),
+ ([1, 2.0, "a"], List[Union[int, float, str]]),
+ ({"a": 1, "b": 2}, Dict[str, int]),
+ ({"a": 1, 2: "b"}, Dict[Union[int, str], Union[str, int]]),
+ (CustomDict(), CustomDict),
+ (ChildCustomDict(), ChildCustomDict),
+ (GenericDict({1: 1}), Dict[int, int]),
+ (ChildGenericDict({1: 1}), Dict[int, int]),
+ ],
+)
+def test_figure_out_type(value, expected):
+ assert figure_out_type(value) == expected
diff --git a/tests/utils/__init__.py b/tests/utils/__init__.py
deleted file mode 100644
index e69de29bb..000000000