Merge remote-tracking branch 'origin/main' into lendemor/add_PTH_rule

This commit is contained in:
Masen Furer 2024-12-13 13:45:03 -08:00
commit 78fa3d31f1
No known key found for this signature in database
GPG Key ID: B0008AD22B3B3A95
33 changed files with 832 additions and 163 deletions

View File

@ -86,7 +86,7 @@ build-backend = "poetry.core.masonry.api"
[tool.ruff]
target-version = "py39"
lint.isort.split-on-trailing-comma = false
lint.select = ["B", "D", "E", "ERA", "F", "FURB", "I", "PTH", "RUF", "SIM", "W"]
lint.select = ["B", "C4", "D", "E", "ERA", "F", "FURB", "I", "PTH", "RUF", "SIM", "W"]
lint.ignore = ["B008", "D205", "E501", "F403", "SIM115", "RUF006", "RUF012"]
lint.pydocstyle.convention = "google"

View File

@ -5,11 +5,15 @@ export function {{tag_name}} () {
{{ hook }}
{% endfor %}
{% for hook, data in component._get_all_hooks().items() if not data.position or data.position == const.hook_position.PRE_TRIGGER %}
{{ hook }}
{% endfor %}
{% for hook in memo_trigger_hooks %}
{{ hook }}
{% endfor %}
{% for hook in component._get_all_hooks() %}
{% for hook, data in component._get_all_hooks().items() if data.position and data.position == const.hook_position.POST_TRIGGER %}
{{ hook }}
{% endfor %}

View File

@ -436,7 +436,7 @@ class App(MiddlewareMixin, LifespanMixin):
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
allow_origins=["*"],
allow_origins=get_config().cors_allowed_origins,
)
@property

View File

@ -45,6 +45,7 @@ class ReflexJinjaEnvironment(Environment):
"on_load_internal": constants.CompileVars.ON_LOAD_INTERNAL,
"update_vars_internal": constants.CompileVars.UPDATE_VARS_INTERNAL,
"frontend_exception_state": constants.CompileVars.FRONTEND_EXCEPTION_STATE_FULL,
"hook_position": constants.Hooks.HookPosition,
}

View File

@ -115,7 +115,7 @@ def compile_imports(import_dict: ParsedImportDict) -> list[dict]:
default, rest = compile_import_statement(fields)
# prevent lib from being rendered on the page if all imports are non rendered kind
if not any({f.render for f in fields}): # type: ignore
if not any(f.render for f in fields): # type: ignore
continue
if not lib:

View File

@ -1208,7 +1208,7 @@ class Component(BaseComponent, ABC):
Yields:
The parent classes that define the method (differently than the base).
"""
seen_methods = set([getattr(Component, method)])
seen_methods = {getattr(Component, method)}
for clz in cls.mro():
if clz is Component:
break
@ -1368,7 +1368,9 @@ class Component(BaseComponent, ABC):
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()
hook_vardata.imports
for hook_vardata in self._get_added_hooks().values()
if hook_vardata is not None
)
return imports.merge_imports(_imports, *other_imports)
@ -1390,15 +1392,9 @@ class Component(BaseComponent, ABC):
# Collect imports from Vars used directly by this component.
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,
),
)
)
var_imports: List[ImmutableParsedImportDict] = [
var_data.imports for var_data in var_datas if var_data is not None
]
added_import_dicts: list[ParsedImportDict] = []
for clz in self._iter_parent_classes_with_method("add_imports"):
@ -1522,7 +1518,7 @@ class Component(BaseComponent, ABC):
**self._get_special_hooks(),
}
def _get_added_hooks(self) -> dict[str, ImportDict]:
def _get_added_hooks(self) -> dict[str, VarData | None]:
"""Get the hooks added via `add_hooks` method.
Returns:
@ -1531,17 +1527,15 @@ class Component(BaseComponent, ABC):
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
code[sub_hook] = None
if str(hook) in code:
code[str(hook)] = imports.merge_imports(code[str(hook)], _imports)
code[str(hook)] = VarData.merge(var_data, code[str(hook)])
else:
code[str(hook)] = _imports
code[str(hook)] = var_data
# 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)
@ -1550,7 +1544,7 @@ class Component(BaseComponent, ABC):
if isinstance(hook, Var):
extract_var_hooks(hook)
else:
code[hook] = {}
code[hook] = None
return code
@ -1592,8 +1586,8 @@ class Component(BaseComponent, ABC):
if hooks is not None:
code[hooks] = None
for hook in self._get_added_hooks():
code[hook] = None
for hook, var_data in self._get_added_hooks().items():
code[hook] = var_data
# Add the hook code for the children.
for child in self.children:
@ -2195,6 +2189,31 @@ class StatefulComponent(BaseComponent):
]
return [var_name]
@staticmethod
def _get_deps_from_event_trigger(event: EventChain | EventSpec | Var) -> set[str]:
"""Get the dependencies accessed by event triggers.
Args:
event: The event trigger to extract deps from.
Returns:
The dependencies accessed by the event triggers.
"""
events: list = [event]
deps = set()
if isinstance(event, EventChain):
events.extend(event.events)
for ev in events:
if isinstance(ev, EventSpec):
for arg in ev.args:
for a in arg:
var_datas = VarData.merge(a._get_all_var_data())
if var_datas and var_datas.deps is not None:
deps |= {str(dep) for dep in var_datas.deps}
return deps
@classmethod
def _get_memoized_event_triggers(
cls,
@ -2231,6 +2250,11 @@ class StatefulComponent(BaseComponent):
# Calculate Var dependencies accessed by the handler for useCallback dep array.
var_deps = ["addEvents", "Event"]
# Get deps from event trigger var data.
var_deps.extend(cls._get_deps_from_event_trigger(event))
# Get deps from hooks.
for arg in event_args:
var_data = arg._get_all_var_data()
if var_data is None:

View File

@ -6,11 +6,12 @@ from typing import Dict, List, Tuple, Union
from reflex.components.base.fragment import Fragment
from reflex.components.tags.tag import Tag
from reflex.constants.compiler import Hooks
from reflex.event import EventChain, EventHandler, passthrough_event_spec
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
from reflex.vars.base import Var, VarData
class Clipboard(Fragment):
@ -72,7 +73,7 @@ class Clipboard(Fragment):
),
}
def add_hooks(self) -> list[str]:
def add_hooks(self) -> list[str | Var[str]]:
"""Add hook to register paste event listener.
Returns:
@ -83,13 +84,14 @@ class Clipboard(Fragment):
return []
if isinstance(on_paste, EventChain):
on_paste = wrap(str(format_prop(on_paste)).strip("{}"), "(")
hook_expr = f"usePasteHandler({self.targets!s}, {self.on_paste_event_actions!s}, {on_paste!s})"
return [
"usePasteHandler(%s, %s, %s)"
% (
str(self.targets),
str(self.on_paste_event_actions),
on_paste,
)
Var(
hook_expr,
_var_type="str",
_var_data=VarData(position=Hooks.HookPosition.POST_TRIGGER),
),
]

View File

@ -71,6 +71,6 @@ class Clipboard(Fragment):
...
def add_imports(self) -> dict[str, ImportVar]: ...
def add_hooks(self) -> list[str]: ...
def add_hooks(self) -> list[str | Var[str]]: ...
clipboard = Clipboard.create

View File

@ -339,8 +339,11 @@ class DataEditor(NoSSRComponent):
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(_js_expr=data_callback) # type: ignore
if self.get_cell_content is not None:
data_callback = self.get_cell_content._js_expr
else:
data_callback = f"getData_{editor_id}"
self.get_cell_content = Var(_js_expr=data_callback) # type: ignore
code = [f"function {data_callback}([col, row])" "{"]

View File

@ -8,6 +8,7 @@ from reflex.event import EventHandler, no_args_event_spec, passthrough_event_spe
from reflex.vars.base import Var
from ..base import LiteralAccentColor, RadixThemesComponent
from .checkbox import Checkbox
LiteralDirType = Literal["ltr", "rtl"]
@ -232,6 +233,15 @@ class ContextMenuSeparator(RadixThemesComponent):
tag = "ContextMenu.Separator"
class ContextMenuCheckbox(Checkbox):
"""The component that contains the checkbox."""
tag = "ContextMenu.CheckboxItem"
# Text to render as shortcut.
shortcut: Var[str]
class ContextMenu(ComponentNamespace):
"""Menu representing a set of actions, displayed at the origin of a pointer right-click or long-press."""
@ -243,6 +253,7 @@ class ContextMenu(ComponentNamespace):
sub_content = staticmethod(ContextMenuSubContent.create)
item = staticmethod(ContextMenuItem.create)
separator = staticmethod(ContextMenuSeparator.create)
checkbox = staticmethod(ContextMenuCheckbox.create)
context_menu = ContextMenu()

View File

@ -12,6 +12,7 @@ from reflex.style import Style
from reflex.vars.base import Var
from ..base import RadixThemesComponent
from .checkbox import Checkbox
LiteralDirType = Literal["ltr", "rtl"]
LiteralSizeType = Literal["1", "2"]
@ -672,6 +673,159 @@ class ContextMenuSeparator(RadixThemesComponent):
"""
...
class ContextMenuCheckbox(Checkbox):
@overload
@classmethod
def create( # type: ignore
cls,
*children,
shortcut: Optional[Union[Var[str], str]] = None,
as_child: Optional[Union[Var[bool], bool]] = None,
size: Optional[
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[
Literal["classic", "soft", "surface"],
Var[Literal["classic", "soft", "surface"]],
]
] = None,
color_scheme: Optional[
Union[
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",
],
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_checked: Optional[Union[Var[bool], bool]] = None,
checked: Optional[Union[Var[bool], bool]] = None,
disabled: Optional[Union[Var[bool], bool]] = None,
required: Optional[Union[Var[bool], bool]] = None,
name: Optional[Union[Var[str], str]] = None,
value: 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, Any]]] = None,
on_blur: Optional[EventType[[], BASE_STATE]] = None,
on_change: Optional[
Union[EventType[[], BASE_STATE], EventType[[bool], BASE_STATE]]
] = None,
on_click: Optional[EventType[[], BASE_STATE]] = None,
on_context_menu: Optional[EventType[[], BASE_STATE]] = None,
on_double_click: Optional[EventType[[], BASE_STATE]] = None,
on_focus: Optional[EventType[[], BASE_STATE]] = None,
on_mount: Optional[EventType[[], BASE_STATE]] = None,
on_mouse_down: Optional[EventType[[], BASE_STATE]] = None,
on_mouse_enter: Optional[EventType[[], BASE_STATE]] = None,
on_mouse_leave: Optional[EventType[[], BASE_STATE]] = None,
on_mouse_move: Optional[EventType[[], BASE_STATE]] = None,
on_mouse_out: Optional[EventType[[], BASE_STATE]] = None,
on_mouse_over: Optional[EventType[[], BASE_STATE]] = None,
on_mouse_up: Optional[EventType[[], BASE_STATE]] = None,
on_scroll: Optional[EventType[[], BASE_STATE]] = None,
on_unmount: Optional[EventType[[], BASE_STATE]] = None,
**props,
) -> "ContextMenuCheckbox":
"""Create a new component instance.
Will prepend "RadixThemes" to the component tag to avoid conflicts with
other UI libraries for common names, like Text and Button.
Args:
*children: Child components.
shortcut: Text to render as shortcut.
as_child: Change the default rendered element for the one passed as a child, merging their props and behavior.
size: Checkbox size "1" - "3"
variant: Variant of checkbox: "classic" | "surface" | "soft"
color_scheme: Override theme color for checkbox
high_contrast: Whether to render the checkbox with higher contrast color against background
default_checked: Whether the checkbox is checked by default
checked: Whether the checkbox is checked
disabled: Whether the checkbox is disabled
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: 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.
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: Component properties.
Returns:
A new component instance.
"""
...
class ContextMenu(ComponentNamespace):
root = staticmethod(ContextMenuRoot.create)
trigger = staticmethod(ContextMenuTrigger.create)
@ -681,5 +835,6 @@ class ContextMenu(ComponentNamespace):
sub_content = staticmethod(ContextMenuSubContent.create)
item = staticmethod(ContextMenuItem.create)
separator = staticmethod(ContextMenuSeparator.create)
checkbox = staticmethod(ContextMenuCheckbox.create)
context_menu = ContextMenu()

View File

@ -79,7 +79,7 @@ class IconButton(elements.Button, RadixLoadingProp, RadixThemesComponent):
else:
size_map_var = Match.create(
props["size"],
*[(size, px) for size, px in RADIX_TO_LUCIDE_SIZE.items()],
*list(RADIX_TO_LUCIDE_SIZE.items()),
12,
)
if not isinstance(size_map_var, Var):

View File

@ -19,7 +19,7 @@ LiteralTextFieldSize = Literal["1", "2", "3"]
LiteralTextFieldVariant = Literal["classic", "surface", "soft"]
class TextFieldRoot(elements.Div, RadixThemesComponent):
class TextFieldRoot(elements.Input, RadixThemesComponent):
"""Captures user input with an optional slot for buttons and icons."""
tag = "TextField.Root"

View File

@ -17,7 +17,7 @@ from ..base import RadixThemesComponent
LiteralTextFieldSize = Literal["1", "2", "3"]
LiteralTextFieldVariant = Literal["classic", "surface", "soft"]
class TextFieldRoot(elements.Div, RadixThemesComponent):
class TextFieldRoot(elements.Input, RadixThemesComponent):
@overload
@classmethod
def create( # type: ignore
@ -120,6 +120,30 @@ class TextFieldRoot(elements.Div, RadixThemesComponent):
type: Optional[Union[Var[str], str]] = None,
value: Optional[Union[Var[Union[float, int, str]], float, int, str]] = None,
list: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = 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_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,
dirname: 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[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[bool, int, str]], bool, int, str]
] = None,
form_target: 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,
multiple: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
pattern: 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,
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[bool, int, str]], bool, int, str]
@ -192,12 +216,12 @@ class TextFieldRoot(elements.Div, RadixThemesComponent):
Args:
*children: The children of the component.
size: Text field size "1" - "3"
size: Specifies the visible width of a text control
variant: Variant of text field: "classic" | "surface" | "soft"
color_scheme: Override theme color for text field
radius: Override theme radius for text field: "none" | "small" | "medium" | "large" | "full"
auto_complete: Whether the input should have autocomplete enabled
default_value: The value of the input when initially rendered.
default_value: The initial value for a text field
disabled: Disables the input
max_length: Specifies the maximum number of characters allowed in the input
min_length: Specifies the minimum number of characters required in the input
@ -208,11 +232,31 @@ class TextFieldRoot(elements.Div, RadixThemesComponent):
type: Specifies the type of input
value: Value of the input
list: References a datalist for suggested options
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.
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
accept: Accepted types of files when the input is file type
alt: Alternate text for input type="image"
auto_focus: Automatically focuses the input when the page loads
capture: Captures media from the user (camera or microphone)
checked: Indicates whether the input is checked (for checkboxes and radio buttons)
default_checked: The initial value (for checkboxes and radio buttons)
dirname: Name part of the input to submit in 'dir' and 'name' pair when form is submitted
form: Associates the input with a form (by id)
form_action: URL to send the form data to (for type="submit" buttons)
form_enc_type: How the form data should be encoded when submitting to the server (for type="submit" buttons)
form_method: HTTP method to use for sending form data (for type="submit" buttons)
form_no_validate: Bypasses form validation when submitting (for type="submit" buttons)
form_target: Specifies where to display the response after submitting the form (for type="submit" buttons)
max: Specifies the maximum value for the input
min: Specifies the minimum value for the input
multiple: Indicates whether multiple values can be entered in an input of the type email or file
pattern: Regex pattern the input's value must match to be valid
src: URL for image inputs
step: Specifies the legal number intervals for an input
use_map: Name of the image map used with the input
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.
@ -457,6 +501,30 @@ class TextField(ComponentNamespace):
type: Optional[Union[Var[str], str]] = None,
value: Optional[Union[Var[Union[float, int, str]], float, int, str]] = None,
list: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = 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_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,
dirname: 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[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[bool, int, str]], bool, int, str]
] = None,
form_target: 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,
multiple: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None,
pattern: 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,
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[bool, int, str]], bool, int, str]
@ -529,12 +597,12 @@ class TextField(ComponentNamespace):
Args:
*children: The children of the component.
size: Text field size "1" - "3"
size: Specifies the visible width of a text control
variant: Variant of text field: "classic" | "surface" | "soft"
color_scheme: Override theme color for text field
radius: Override theme radius for text field: "none" | "small" | "medium" | "large" | "full"
auto_complete: Whether the input should have autocomplete enabled
default_value: The value of the input when initially rendered.
default_value: The initial value for a text field
disabled: Disables the input
max_length: Specifies the maximum number of characters allowed in the input
min_length: Specifies the minimum number of characters required in the input
@ -545,11 +613,31 @@ class TextField(ComponentNamespace):
type: Specifies the type of input
value: Value of the input
list: References a datalist for suggested options
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.
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
accept: Accepted types of files when the input is file type
alt: Alternate text for input type="image"
auto_focus: Automatically focuses the input when the page loads
capture: Captures media from the user (camera or microphone)
checked: Indicates whether the input is checked (for checkboxes and radio buttons)
default_checked: The initial value (for checkboxes and radio buttons)
dirname: Name part of the input to submit in 'dir' and 'name' pair when form is submitted
form: Associates the input with a form (by id)
form_action: URL to send the form data to (for type="submit" buttons)
form_enc_type: How the form data should be encoded when submitting to the server (for type="submit" buttons)
form_method: HTTP method to use for sending form data (for type="submit" buttons)
form_no_validate: Bypasses form validation when submitting (for type="submit" buttons)
form_target: Specifies where to display the response after submitting the form (for type="submit" buttons)
max: Specifies the maximum value for the input
min: Specifies the minimum value for the input
multiple: Indicates whether multiple values can be entered in an input of the type email or file
pattern: Regex pattern the input's value must match to be valid
src: URL for image inputs
step: Specifies the legal number intervals for an input
use_map: Name of the image map used with the input
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.

View File

@ -84,10 +84,10 @@ class ChartBase(RechartsCharts):
cls._ensure_valid_dimension("width", width)
cls._ensure_valid_dimension("height", height)
dim_props = dict(
width=width or "100%",
height=height or "100%",
)
dim_props = {
"width": width or "100%",
"height": height or "100%",
}
# Provide min dimensions so the graph always appears, even if the outer container is zero-size.
if width is None:
dim_props["min_width"] = 200

View File

@ -132,6 +132,12 @@ class Hooks(SimpleNamespace):
}
})"""
class HookPosition(enum.Enum):
"""The position of the hook in the component."""
PRE_TRIGGER = "pre_trigger"
POST_TRIGGER = "post_trigger"
class MemoizationDisposition(enum.Enum):
"""The conditions under which a component should be memoized."""

View File

@ -31,7 +31,7 @@ class RouteVar(SimpleNamespace):
# This subset of router_data is included in chained on_load events.
ROUTER_DATA_INCLUDE = set((RouteVar.PATH, RouteVar.ORIGIN, RouteVar.QUERY))
ROUTER_DATA_INCLUDE = {RouteVar.PATH, RouteVar.ORIGIN, RouteVar.QUERY}
class RouteRegex(SimpleNamespace):

View File

@ -25,6 +25,7 @@ from typing import (
overload,
)
import typing_extensions
from typing_extensions import (
Concatenate,
ParamSpec,
@ -296,7 +297,7 @@ class EventSpec(EventActionsMixin):
handler: EventHandler,
event_actions: Dict[str, Union[bool, int]] | None = None,
client_handler_name: str = "",
args: Tuple[Tuple[Var, Var], ...] = tuple(),
args: Tuple[Tuple[Var, Var], ...] = (),
):
"""Initialize an EventSpec.
@ -311,7 +312,7 @@ class EventSpec(EventActionsMixin):
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())
object.__setattr__(self, "args", args or ())
def with_args(self, args: Tuple[Tuple[Var, Var], ...]) -> EventSpec:
"""Copy the event spec, with updated args.
@ -513,7 +514,7 @@ def no_args_event_spec() -> Tuple[()]:
Returns:
An empty tuple.
"""
return tuple() # type: ignore
return () # type: ignore
# These chains can be used for their side effects when no other events are desired.
@ -714,26 +715,61 @@ def server_side(name: str, sig: inspect.Signature, **kwargs) -> EventSpec:
)
@overload
def redirect(
path: str | Var[str],
external: Optional[bool] = False,
replace: Optional[bool] = False,
is_external: Optional[bool] = None,
replace: bool = False,
) -> EventSpec: ...
@overload
@typing_extensions.deprecated("`external` is deprecated use `is_external` instead")
def redirect(
path: str | Var[str],
is_external: Optional[bool] = None,
replace: bool = False,
external: Optional[bool] = None,
) -> EventSpec: ...
def redirect(
path: str | Var[str],
is_external: Optional[bool] = None,
replace: bool = False,
external: Optional[bool] = None,
) -> EventSpec:
"""Redirect to a new path.
Args:
path: The path to redirect to.
external: Whether to open in new tab or not.
is_external: Whether to open in new tab or not.
replace: If True, the current page will not create a new history entry.
external(Deprecated): Whether to open in new tab or not.
Returns:
An event to redirect to the path.
"""
if external is not None:
console.deprecate(
"The `external` prop in `rx.redirect`",
"use `is_external` instead.",
"0.6.6",
"0.7.0",
)
# is_external should take precedence over external.
is_external = (
(False if external is None else external)
if is_external is None
else is_external
)
return server_side(
"_redirect",
get_fn_signature(redirect),
path=path,
external=external,
external=is_external,
replace=replace,
)
@ -1101,9 +1137,7 @@ def run_script(
Var(javascript_code) if isinstance(javascript_code, str) else javascript_code
)
return call_function(
ArgsFunctionOperation.create(tuple(), javascript_code), callback
)
return call_function(ArgsFunctionOperation.create((), javascript_code), callback)
def get_event(state, event):
@ -1455,7 +1489,7 @@ def get_handler_args(
"""
args = inspect.getfullargspec(event_spec.handler.fn).args
return event_spec.args if len(args) > 1 else tuple()
return event_spec.args if len(args) > 1 else ()
def fix_events(

View File

@ -52,12 +52,12 @@ def get_engine_args(url: str | None = None) -> dict[str, Any]:
Returns:
The database engine arguments as a dict.
"""
kwargs: dict[str, Any] = dict(
kwargs: dict[str, Any] = {
# Print the SQL queries if the log level is INFO or lower.
echo=environment.SQLALCHEMY_ECHO.get(),
"echo": environment.SQLALCHEMY_ECHO.get(),
# Check connections before returning them.
pool_pre_ping=environment.SQLALCHEMY_POOL_PRE_PING.get(),
)
"pool_pre_ping": environment.SQLALCHEMY_POOL_PRE_PING.get(),
}
conf = get_config()
url = url or conf.db_url
if url is not None and url.startswith("sqlite"):

View File

@ -442,13 +442,13 @@ def deploy(
hidden=True,
),
regions: List[str] = typer.Option(
list(),
[],
"-r",
"--region",
help="The regions to deploy to. `reflex cloud regions` For multiple envs, repeat this option, e.g. --region sjc --region iad",
),
envs: List[str] = typer.Option(
list(),
[],
"--env",
help="The environment variables to set: <key>=<value>. For multiple envs, repeat this option, e.g. --env k1=v2 --env k2=v2.",
),

View File

@ -437,9 +437,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()}
)
self._backend_vars = copy.deepcopy(self.backend_vars)
def __repr__(self) -> str:
"""Get the string representation of the state.
@ -523,9 +521,7 @@ 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.get_name() in set(
c.get_name() for c in parent_state.class_subclasses
):
if cls.get_name() in {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. "
@ -788,11 +784,11 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
)
# ComputedVar with cache=False always need to be recomputed
cls._always_dirty_computed_vars = set(
cls._always_dirty_computed_vars = {
cvar_name
for cvar_name, cvar in cls.computed_vars.items()
if not cvar._cache
)
}
# Any substate containing a ComputedVar with cache=False always needs to be recomputed
if cls._always_dirty_computed_vars:
@ -1862,11 +1858,11 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
Returns:
Set of computed vars to include in the delta.
"""
return set(
return {
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
@ -1880,12 +1876,12 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
Returns:
Set of computed vars to include in the delta.
"""
return set(
return {
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
def _potentially_dirty_substates(cls) -> set[Type[BaseState]]:
@ -1895,16 +1891,16 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
Set of State classes that may need to be fetched to recalc computed vars.
"""
# _always_dirty_substates need to be fetched to recalc computed vars.
fetch_substates = set(
fetch_substates = {
cls.get_class_substate((cls.get_name(), *substate_name.split(".")))
for substate_name in cls._always_dirty_substates
)
}
for dependent_substates in cls._substate_var_dependencies.values():
fetch_substates.update(
set(
{
cls.get_class_substate((cls.get_name(), *substate_name.split(".")))
for substate_name in dependent_substates
)
}
)
return fetch_substates
@ -2206,7 +2202,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
return md5(
pickle.dumps(
list(sorted(_field_tuple(field_name) for field_name in cls.base_vars))
sorted(_field_tuple(field_name) for field_name in cls.base_vars)
)
).hexdigest()
@ -3354,7 +3350,7 @@ class StateManagerRedis(StateManager):
state_cls = self.state.get_class_substate(state_path)
else:
raise RuntimeError(
"StateManagerRedis requires token to be specified in the form of {token}_{state_full_name}"
f"StateManagerRedis requires token to be specified in the form of {{token}}_{{state_full_name}}, but got {token}"
)
# The deserialized or newly created (sub)state instance.
@ -3654,33 +3650,30 @@ class MutableProxy(wrapt.ObjectProxy):
"""A proxy for a mutable object that tracks changes."""
# Methods on wrapped objects which should mark the state as dirty.
__mark_dirty_attrs__ = set(
[
"add",
"append",
"clear",
"difference_update",
"discard",
"extend",
"insert",
"intersection_update",
"pop",
"popitem",
"remove",
"reverse",
"setdefault",
"sort",
"symmetric_difference_update",
"update",
]
)
__mark_dirty_attrs__ = {
"add",
"append",
"clear",
"difference_update",
"discard",
"extend",
"insert",
"intersection_update",
"pop",
"popitem",
"remove",
"reverse",
"setdefault",
"sort",
"symmetric_difference_update",
"update",
}
# Methods on wrapped objects might return mutable objects that should be tracked.
__wrap_mutable_attrs__ = set(
[
"get",
"setdefault",
]
)
__wrap_mutable_attrs__ = {
"get",
"setdefault",
}
# These internal attributes on rx.Base should NOT be wrapped in a MutableProxy.
__never_wrap_base_attrs__ = set(Base.__dict__) - {"set"} | set(
@ -3723,7 +3716,7 @@ class MutableProxy(wrapt.ObjectProxy):
self,
wrapped=None,
instance=None,
args=tuple(),
args=(),
kwargs=None,
) -> Any:
"""Mark the state as dirty, then call a wrapped function.
@ -3979,7 +3972,7 @@ class ImmutableMutableProxy(MutableProxy):
self,
wrapped=None,
instance=None,
args=tuple(),
args=(),
kwargs=None,
) -> Any:
"""Raise an exception when an attempt is made to modify the object.

View File

@ -117,7 +117,7 @@ def run_process_and_launch_url(run_command: list[str], backend_present=True):
console.print("New packages detected: Updating app...")
else:
if any(
[x in line for x in ("bin executable does not exist on disk",)]
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"

View File

@ -701,7 +701,7 @@ def _update_next_config(
}
if transpile_packages:
next_config["transpilePackages"] = list(
set((format_library_name(p) for p in transpile_packages))
{format_library_name(p) for p in transpile_packages}
)
if export:
next_config["output"] = "export"
@ -927,7 +927,7 @@ def cached_procedure(cache_file: str, payload_fn: Callable[..., str]):
@cached_procedure(
cache_file=str(get_web_dir() / "reflex.install_frontend_packages.cached"),
payload_fn=lambda p, c: f"{sorted(list(p))!r},{c.json()}",
payload_fn=lambda p, c: f"{sorted(p)!r},{c.json()}",
)
def install_frontend_packages(packages: set[str], config: Config):
"""Installs the base and custom frontend packages.
@ -1302,7 +1302,7 @@ def fetch_app_templates(version: str) -> dict[str, Template]:
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))
known_fields = {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}
)

View File

@ -9,6 +9,7 @@ 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 .datetime import DateTimeVar as DateTimeVar
from .function import FunctionStringVar as FunctionStringVar
from .function import FunctionVar as FunctionVar
from .function import VarOperationCall as VarOperationCall

View File

@ -42,7 +42,8 @@ from typing_extensions import ParamSpec, TypeGuard, deprecated, get_type_hints,
from reflex import constants
from reflex.base import Base
from reflex.utils import console, imports, serializers, types
from reflex.constants.compiler import Hooks
from reflex.utils import console, exceptions, imports, serializers, types
from reflex.utils.exceptions import (
VarAttributeError,
VarDependencyError,
@ -115,12 +116,20 @@ class VarData:
# Hooks that need to be present in the component to render this var
hooks: Tuple[str, ...] = dataclasses.field(default_factory=tuple)
# Dependencies of the var
deps: Tuple[Var, ...] = dataclasses.field(default_factory=tuple)
# Position of the hook in the component
position: Hooks.HookPosition | None = None
def __init__(
self,
state: str = "",
field_name: str = "",
imports: ImportDict | ParsedImportDict | None = None,
hooks: dict[str, None] | None = None,
deps: list[Var] | None = None,
position: Hooks.HookPosition | None = None,
):
"""Initialize the var data.
@ -129,6 +138,8 @@ class VarData:
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.
deps: Dependencies of the var for useCallback.
position: Position of the hook in the component.
"""
immutable_imports: ImmutableParsedImportDict = tuple(
sorted(
@ -139,6 +150,8 @@ class VarData:
object.__setattr__(self, "field_name", field_name)
object.__setattr__(self, "imports", immutable_imports)
object.__setattr__(self, "hooks", tuple(hooks or {}))
object.__setattr__(self, "deps", tuple(deps or []))
object.__setattr__(self, "position", position or None)
def old_school_imports(self) -> ImportDict:
"""Return the imports as a mutable dict.
@ -146,7 +159,7 @@ class VarData:
Returns:
The imports as a mutable dict.
"""
return dict((k, list(v)) for k, v in self.imports)
return {k: list(v) for k, v in self.imports}
def merge(*all: VarData | None) -> VarData | None:
"""Merge multiple var data objects.
@ -154,6 +167,9 @@ class VarData:
Args:
*all: The var data objects to merge.
Raises:
ReflexError: If trying to merge VarData with different positions.
Returns:
The merged var data object.
@ -184,12 +200,32 @@ class VarData:
*(var_data.imports for var_data in all_var_datas)
)
if state or _imports or hooks or field_name:
deps = [dep for var_data in all_var_datas for dep in var_data.deps]
positions = list(
{
var_data.position
for var_data in all_var_datas
if var_data.position is not None
}
)
if positions:
if len(positions) > 1:
raise exceptions.ReflexError(
f"Cannot merge var data with different positions: {positions}"
)
position = positions[0]
else:
position = None
if state or _imports or hooks or field_name or deps or position:
return VarData(
state=state,
field_name=field_name,
imports=_imports,
hooks=hooks,
deps=deps,
position=position,
)
return None
@ -200,7 +236,14 @@ class VarData:
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)
return bool(
self.state
or self.imports
or self.hooks
or self.field_name
or self.deps
or self.position
)
@classmethod
def from_state(cls, state: Type[BaseState] | str, field_name: str = "") -> VarData:
@ -480,7 +523,6 @@ class Var(Generic[VAR_TYPE]):
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,
@ -1591,14 +1633,12 @@ class CachedVarOperation:
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
),
*(
value._get_all_var_data() if isinstance(value, Var) else None
for value in (
getattr(self, field.name)
for field in dataclasses.fields(self) # type: ignore
)
),
self._var_data,
)
@ -1889,20 +1929,20 @@ class ComputedVar(Var[RETURN_TYPE]):
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(
field_values = {
"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())
@ -2371,10 +2411,7 @@ class CustomVarOperation(CachedVarOperation, Var[T]):
The cached VarData.
"""
return VarData.merge(
*map(
lambda arg: arg[1]._get_all_var_data(),
self._args,
),
*(arg[1]._get_all_var_data() for arg in self._args),
self._return._get_all_var_data(),
self._var_data,
)

222
reflex/vars/datetime.py Normal file
View File

@ -0,0 +1,222 @@
"""Immutable datetime and date vars."""
from __future__ import annotations
import dataclasses
import sys
from datetime import date, datetime
from typing import Any, NoReturn, TypeVar, Union, overload
from reflex.utils.exceptions import VarTypeError
from reflex.vars.number import BooleanVar
from .base import (
CustomVarOperationReturn,
LiteralVar,
Var,
VarData,
var_operation,
var_operation_return,
)
DATETIME_T = TypeVar("DATETIME_T", datetime, date)
datetime_types = Union[datetime, date]
def raise_var_type_error():
"""Raise a VarTypeError.
Raises:
VarTypeError: Cannot compare a datetime object with a non-datetime object.
"""
raise VarTypeError("Cannot compare a datetime object with a non-datetime object.")
class DateTimeVar(Var[DATETIME_T], python_types=(datetime, date)):
"""A variable that holds a datetime or date object."""
@overload
def __lt__(self, other: datetime_types) -> BooleanVar: ...
@overload
def __lt__(self, other: NoReturn) -> NoReturn: ...
def __lt__(self, other: Any):
"""Less than comparison.
Args:
other: The other datetime to compare.
Returns:
The result of the comparison.
"""
if not isinstance(other, DATETIME_TYPES):
raise_var_type_error()
return date_lt_operation(self, other)
@overload
def __le__(self, other: datetime_types) -> BooleanVar: ...
@overload
def __le__(self, other: NoReturn) -> NoReturn: ...
def __le__(self, other: Any):
"""Less than or equal comparison.
Args:
other: The other datetime to compare.
Returns:
The result of the comparison.
"""
if not isinstance(other, DATETIME_TYPES):
raise_var_type_error()
return date_le_operation(self, other)
@overload
def __gt__(self, other: datetime_types) -> BooleanVar: ...
@overload
def __gt__(self, other: NoReturn) -> NoReturn: ...
def __gt__(self, other: Any):
"""Greater than comparison.
Args:
other: The other datetime to compare.
Returns:
The result of the comparison.
"""
if not isinstance(other, DATETIME_TYPES):
raise_var_type_error()
return date_gt_operation(self, other)
@overload
def __ge__(self, other: datetime_types) -> BooleanVar: ...
@overload
def __ge__(self, other: NoReturn) -> NoReturn: ...
def __ge__(self, other: Any):
"""Greater than or equal comparison.
Args:
other: The other datetime to compare.
Returns:
The result of the comparison.
"""
if not isinstance(other, DATETIME_TYPES):
raise_var_type_error()
return date_ge_operation(self, other)
@var_operation
def date_gt_operation(lhs: Var | Any, rhs: Var | Any) -> CustomVarOperationReturn:
"""Greater than comparison.
Args:
lhs: The left-hand side of the operation.
rhs: The right-hand side of the operation.
Returns:
The result of the operation.
"""
return date_compare_operation(rhs, lhs, strict=True)
@var_operation
def date_lt_operation(lhs: Var | Any, rhs: Var | Any) -> CustomVarOperationReturn:
"""Less than comparison.
Args:
lhs: The left-hand side of the operation.
rhs: The right-hand side of the operation.
Returns:
The result of the operation.
"""
return date_compare_operation(lhs, rhs, strict=True)
@var_operation
def date_le_operation(lhs: Var | Any, rhs: Var | Any) -> CustomVarOperationReturn:
"""Less than or equal comparison.
Args:
lhs: The left-hand side of the operation.
rhs: The right-hand side of the operation.
Returns:
The result of the operation.
"""
return date_compare_operation(lhs, rhs)
@var_operation
def date_ge_operation(lhs: Var | Any, rhs: Var | Any) -> CustomVarOperationReturn:
"""Greater than or equal comparison.
Args:
lhs: The left-hand side of the operation.
rhs: The right-hand side of the operation.
Returns:
The result of the operation.
"""
return date_compare_operation(rhs, lhs)
def date_compare_operation(
lhs: DateTimeVar[DATETIME_T] | Any,
rhs: DateTimeVar[DATETIME_T] | Any,
strict: bool = False,
) -> CustomVarOperationReturn:
"""Check if the value is less than the other value.
Args:
lhs: The left-hand side of the operation.
rhs: The right-hand side of the operation.
strict: Whether to use strict comparison.
Returns:
The result of the operation.
"""
return var_operation_return(
f"({lhs} { '<' if strict else '<='} {rhs})",
bool,
)
@dataclasses.dataclass(
eq=False,
frozen=True,
**{"slots": True} if sys.version_info >= (3, 10) else {},
)
class LiteralDatetimeVar(LiteralVar, DateTimeVar):
"""Base class for immutable datetime and date vars."""
_var_value: datetime | date = dataclasses.field(default=datetime.now())
@classmethod
def create(cls, value: datetime | date, _var_data: VarData | None = None):
"""Create a new instance of the class.
Args:
value: The value to set.
Returns:
LiteralDatetimeVar: The new instance of the class.
"""
js_expr = f'"{value!s}"'
return cls(
_js_expr=js_expr,
_var_type=type(value),
_var_value=value,
_var_data=_var_data,
)
DATETIME_TYPES = (datetime, date, DateTimeVar)

View File

@ -292,7 +292,7 @@ class VarOperationCall(Generic[P, R], CachedVarOperation, Var[R]):
class DestructuredArg:
"""Class for destructured arguments."""
fields: Tuple[str, ...] = tuple()
fields: Tuple[str, ...] = ()
rest: Optional[str] = None
def to_javascript(self) -> str:
@ -314,7 +314,7 @@ class DestructuredArg:
class FunctionArgs:
"""Class for function arguments."""
args: Tuple[Union[str, DestructuredArg], ...] = tuple()
args: Tuple[Union[str, DestructuredArg], ...] = ()
rest: Optional[str] = None

View File

@ -51,7 +51,7 @@ def raise_unsupported_operand_types(
VarTypeError: The operand types are unsupported.
"""
raise VarTypeError(
f"Unsupported Operand type(s) for {operator}: {', '.join(map(lambda t: t.__name__, operands_types))}"
f"Unsupported Operand type(s) for {operator}: {', '.join(t.__name__ for t in operands_types)}"
)

View File

@ -1177,7 +1177,7 @@ class ArrayVar(Var[ARRAY_VAR_TYPE], python_types=(list, tuple, set)):
if num_args == 0:
return_value = fn()
function_var = ArgsFunctionOperation.create(tuple(), return_value)
function_var = ArgsFunctionOperation.create((), return_value)
else:
# generic number var
number_var = Var("").to(NumberVar, int)

View File

@ -0,0 +1,87 @@
from typing import Generator
import pytest
from playwright.sync_api import Page, expect
from reflex.testing import AppHarness
def DatetimeOperationsApp():
from datetime import datetime
import reflex as rx
class DtOperationsState(rx.State):
date1: datetime = datetime(2021, 1, 1)
date2: datetime = datetime(2031, 1, 1)
date3: datetime = datetime(2021, 1, 1)
app = rx.App(state=DtOperationsState)
@app.add_page
def index():
return rx.vstack(
rx.text(DtOperationsState.date1, id="date1"),
rx.text(DtOperationsState.date2, id="date2"),
rx.text(DtOperationsState.date3, id="date3"),
rx.text("Operations between date1 and date2"),
rx.text(DtOperationsState.date1 == DtOperationsState.date2, id="1_eq_2"),
rx.text(DtOperationsState.date1 != DtOperationsState.date2, id="1_neq_2"),
rx.text(DtOperationsState.date1 < DtOperationsState.date2, id="1_lt_2"),
rx.text(DtOperationsState.date1 <= DtOperationsState.date2, id="1_le_2"),
rx.text(DtOperationsState.date1 > DtOperationsState.date2, id="1_gt_2"),
rx.text(DtOperationsState.date1 >= DtOperationsState.date2, id="1_ge_2"),
rx.text("Operations between date1 and date3"),
rx.text(DtOperationsState.date1 == DtOperationsState.date3, id="1_eq_3"),
rx.text(DtOperationsState.date1 != DtOperationsState.date3, id="1_neq_3"),
rx.text(DtOperationsState.date1 < DtOperationsState.date3, id="1_lt_3"),
rx.text(DtOperationsState.date1 <= DtOperationsState.date3, id="1_le_3"),
rx.text(DtOperationsState.date1 > DtOperationsState.date3, id="1_gt_3"),
rx.text(DtOperationsState.date1 >= DtOperationsState.date3, id="1_ge_3"),
)
@pytest.fixture()
def datetime_operations_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("datetime_operations_app"),
app_source=DatetimeOperationsApp, # type: ignore
) as harness:
assert harness.app_instance is not None, "app is not running"
yield harness
def test_datetime_operations(datetime_operations_app: AppHarness, page: Page):
assert datetime_operations_app.frontend_url is not None
page.goto(datetime_operations_app.frontend_url)
expect(page).to_have_url(datetime_operations_app.frontend_url + "/")
# Check the actual values
expect(page.locator("id=date1")).to_have_text("2021-01-01 00:00:00")
expect(page.locator("id=date2")).to_have_text("2031-01-01 00:00:00")
expect(page.locator("id=date3")).to_have_text("2021-01-01 00:00:00")
# Check the operations between date1 and date2
expect(page.locator("id=1_eq_2")).to_have_text("false")
expect(page.locator("id=1_neq_2")).to_have_text("true")
expect(page.locator("id=1_lt_2")).to_have_text("true")
expect(page.locator("id=1_le_2")).to_have_text("true")
expect(page.locator("id=1_gt_2")).to_have_text("false")
expect(page.locator("id=1_ge_2")).to_have_text("false")
# Check the operations between date1 and date3
expect(page.locator("id=1_eq_3")).to_have_text("true")
expect(page.locator("id=1_neq_3")).to_have_text("false")
expect(page.locator("id=1_lt_3")).to_have_text("false")
expect(page.locator("id=1_le_3")).to_have_text("true")
expect(page.locator("id=1_gt_3")).to_have_text("false")
expect(page.locator("id=1_ge_3")).to_have_text("true")

View File

@ -12,7 +12,7 @@ def test_websocket_target_url():
url = WebsocketTargetURL.create()
var_data = url._get_all_var_data()
assert var_data is not None
assert sorted(tuple((key for key, _ in var_data.imports))) == sorted(
assert sorted(key for key, _ in var_data.imports) == sorted(
("$/utils/state", "$/env.json")
)
@ -20,7 +20,7 @@ def test_websocket_target_url():
def test_connection_banner():
banner = ConnectionBanner.create()
_imports = banner._get_all_imports(collapse=True)
assert sorted(tuple(_imports)) == sorted(
assert sorted(_imports) == sorted(
(
"react",
"$/utils/context",
@ -38,7 +38,7 @@ def test_connection_banner():
def test_connection_modal():
modal = ConnectionModal.create()
_imports = modal._get_all_imports(collapse=True)
assert sorted(tuple(_imports)) == sorted(
assert sorted(_imports) == sorted(
(
"react",
"$/utils/context",

View File

@ -372,7 +372,7 @@ def test_basic_operations(TestObj):
"var, expected",
[
(v([1, 2, 3]), "[1, 2, 3]"),
(v(set([1, 2, 3])), "[1, 2, 3]"),
(v({1, 2, 3}), "[1, 2, 3]"),
(v(["1", "2", "3"]), '["1", "2", "3"]'),
(
Var(_js_expr="foo")._var_set_state("state").to(list),
@ -903,7 +903,7 @@ def test_literal_var():
True,
False,
None,
set([1, 2, 3]),
{1, 2, 3},
]
)
assert (

View File

@ -222,6 +222,7 @@ def test_serialize(value: Any, expected: str):
'"2021-01-01 01:01:01.000001"',
True,
),
(datetime.date(2021, 1, 1), '"2021-01-01"', True),
(Color(color="slate", shade=1), '"var(--slate-1)"', True),
(BaseSubclass, '"BaseSubclass"', True),
(Path(), '"."', True),