-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathevent.py
More file actions
2388 lines (1907 loc) ยท 71 KB
/
event.py
File metadata and controls
2388 lines (1907 loc) ยท 71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Define event classes to connect the frontend and backend."""
import dataclasses
import inspect
import types
import urllib.parse
from base64 import b64encode
from collections.abc import Callable, Mapping, Sequence
from functools import lru_cache, partial
from typing import (
TYPE_CHECKING,
Annotated,
Any,
Generic,
NoReturn,
Protocol,
TypeVar,
get_args,
get_origin,
get_type_hints,
overload,
)
from typing_extensions import Self, TypeAliasType, TypedDict, TypeVarTuple, Unpack
from reflex import constants
from reflex.constants.compiler import CompileVars, Hooks, Imports
from reflex.constants.state import FRONTEND_EVENT_STATE
from reflex.utils import format
from reflex.utils.decorator import once
from reflex.utils.exceptions import (
EventFnArgMismatchError,
EventHandlerArgTypeMismatchError,
MissingAnnotationError,
)
from reflex.utils.types import (
ArgsSpec,
GenericType,
Unset,
safe_issubclass,
typehint_issubclass,
)
from reflex.vars import VarData
from reflex.vars.base import LiteralVar, Var
from reflex.vars.function import (
ArgsFunctionOperation,
ArgsFunctionOperationBuilder,
BuilderFunctionVar,
FunctionArgs,
FunctionStringVar,
FunctionVar,
VarOperationCall,
)
from reflex.vars.object import ObjectVar
@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.
token: str
# The event name.
name: str
# The routing data where event occurred
router_data: dict[str, Any] = dataclasses.field(default_factory=dict)
# The event payload.
payload: dict[str, Any] = dataclasses.field(default_factory=dict)
@property
def substate_token(self) -> str:
"""Get the substate token for the event.
Returns:
The substate token.
"""
substate = self.name.rpartition(".")[0]
return f"{self.token}_{substate}"
_EVENT_FIELDS: set[str] = {f.name for f in dataclasses.fields(Event)}
BACKGROUND_TASK_MARKER = "_reflex_background_task"
@dataclasses.dataclass(
init=True,
frozen=True,
kw_only=True,
)
class EventActionsMixin:
"""Mixin for DOM event actions."""
# Whether to `preventDefault` or `stopPropagation` on the event.
event_actions: dict[str, bool | int] = dataclasses.field(default_factory=dict)
@property
def stop_propagation(self) -> Self:
"""Stop the event from bubbling up the DOM tree.
Returns:
New EventHandler-like with stopPropagation set to True.
"""
return dataclasses.replace(
self,
event_actions={**self.event_actions, "stopPropagation": True},
)
@property
def prevent_default(self) -> Self:
"""Prevent the default behavior of the event.
Returns:
New EventHandler-like with preventDefault set to True.
"""
return dataclasses.replace(
self,
event_actions={**self.event_actions, "preventDefault": True},
)
def throttle(self, limit_ms: int) -> Self:
"""Throttle the event handler.
Args:
limit_ms: The time in milliseconds to throttle the event handler.
Returns:
New EventHandler-like with throttle set to limit_ms.
"""
return dataclasses.replace(
self,
event_actions={**self.event_actions, "throttle": limit_ms},
)
def debounce(self, delay_ms: int) -> Self:
"""Debounce the event handler.
Args:
delay_ms: The time in milliseconds to debounce the event handler.
Returns:
New EventHandler-like with debounce set to delay_ms.
"""
return dataclasses.replace(
self,
event_actions={**self.event_actions, "debounce": delay_ms},
)
@property
def temporal(self) -> Self:
"""Do not queue the event if the backend is down.
Returns:
New EventHandler-like with temporal set to True.
"""
return dataclasses.replace(
self,
event_actions={**self.event_actions, "temporal": True},
)
@dataclasses.dataclass(
init=True,
frozen=True,
kw_only=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 = 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 = dataclasses.field(default="")
def __hash__(self):
"""Get the hash of the event handler.
Returns:
The hash of the event handler.
"""
return hash((tuple(self.event_actions.items()), self.fn, self.state_full_name))
def get_parameters(self) -> Mapping[str, inspect.Parameter]:
"""Get the parameters of the function.
Returns:
The parameters of the function.
"""
if self.fn is None:
return {}
return inspect.signature(self.fn).parameters
@property
def _parameters(self) -> Mapping[str, inspect.Parameter]:
"""Get the parameters of the function.
Returns:
The parameters of the function.
"""
if (parameters := getattr(self, "__parameters", None)) is None:
parameters = {**self.get_parameters()}
object.__setattr__(self, "__parameters", parameters)
return parameters
@classmethod
def __class_getitem__(cls, args_spec: str) -> Annotated:
"""Get a typed EventHandler.
Args:
args_spec: The args_spec of the EventHandler.
Returns:
The EventHandler class item.
"""
return Annotated[cls, args_spec]
@property
def is_background(self) -> bool:
"""Whether the event handler is a background task.
Returns:
True if the event handler is marked as a background task.
"""
return getattr(self.fn, BACKGROUND_TASK_MARKER, False)
def __call__(self, *args: Any, **kwargs: Any) -> "EventSpec":
"""Pass arguments to the handler to get an event spec.
This method configures event handlers that take in arguments.
Args:
*args: The arguments to pass to the handler.
**kwargs: The keyword arguments to pass to the handler.
Returns:
The event spec, containing both the function and args.
Raises:
EventHandlerTypeError: If the arguments are invalid.
"""
from reflex.utils.exceptions import EventHandlerTypeError
# Get the function args.
fn_args = list(self._parameters)[1:]
if not isinstance(
repeated_arg := next(
(kwarg for kwarg in kwargs if kwarg in fn_args[: len(args)]), Unset()
),
Unset,
):
msg = f"Event handler {self.fn.__name__} received repeated argument {repeated_arg}."
raise EventHandlerTypeError(msg)
if not isinstance(
extra_arg := next(
(kwarg for kwarg in kwargs if kwarg not in fn_args), Unset()
),
Unset,
):
msg = (
f"Event handler {self.fn.__name__} received extra argument {extra_arg}."
)
raise EventHandlerTypeError(msg)
fn_args = fn_args[: len(args)] + list(kwargs)
fn_args = (Var(_js_expr=arg) for arg in fn_args)
# Construct the payload.
values = []
for arg in [*args, *kwargs.values()]:
# Special case for file uploads.
if isinstance(arg, FileUpload):
return arg.as_event_spec(handler=self)
# Otherwise, convert to JSON.
try:
values.append(LiteralVar.create(arg))
except TypeError as e:
msg = f"Arguments to event handlers must be Vars or JSON-serializable. Got {arg} of type {type(arg)}."
raise EventHandlerTypeError(msg) from e
payload = tuple(zip(fn_args, values, strict=False))
# Return the event spec.
return EventSpec(
handler=self, args=payload, event_actions=self.event_actions.copy()
)
@dataclasses.dataclass(
init=True,
frozen=True,
kw_only=True,
)
class EventSpec(EventActionsMixin):
"""An event specification.
Whereas an Event object is passed during runtime, a spec is used
during compile time to outline the structure of an event.
"""
# The event handler.
handler: EventHandler = dataclasses.field(default=None) # pyright: ignore [reportAssignmentType]
# The handler on the client to process event.
client_handler_name: str = dataclasses.field(default="")
# The arguments to pass to the function.
args: tuple[tuple[Var, Var], ...] = dataclasses.field(default_factory=tuple)
def __init__(
self,
handler: EventHandler,
event_actions: dict[str, bool | int] | None = None,
client_handler_name: str = "",
args: tuple[tuple[Var, Var], ...] = (),
):
"""Initialize an EventSpec.
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 ())
def with_args(self, args: tuple[tuple[Var, Var], ...]) -> "EventSpec":
"""Copy the event spec, with updated args.
Args:
args: The new args to pass to the function.
Returns:
A copy of the event spec, with the new args.
"""
return type(self)(
handler=self.handler,
client_handler_name=self.client_handler_name,
args=args,
event_actions=self.event_actions.copy(),
)
def add_args(self, *args: Var) -> "EventSpec":
"""Add arguments to the event spec.
Args:
*args: The arguments to add positionally.
Returns:
The event spec with the new arguments.
Raises:
EventHandlerTypeError: If the arguments are invalid.
"""
from reflex.utils.exceptions import EventHandlerTypeError
# Get the remaining unfilled function args.
fn_args = list(self.handler._parameters)[1 + len(self.args) :]
fn_args = (Var(_js_expr=arg) for arg in fn_args)
# Construct the payload.
values = []
arg = None
try:
for arg in args:
values.append(LiteralVar.create(value=arg)) # noqa: PERF401, RUF100
except TypeError as e:
msg = f"Arguments to event handlers must be Vars or JSON-serializable. Got {arg} of type {type(arg)}."
raise EventHandlerTypeError(msg) from e
new_payload = tuple(zip(fn_args, values, strict=False))
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.
This is used as a compatibility shim for replacing EventSpec objects in the
API with functions that return a family of EventSpec.
"""
fn: Callable[..., EventSpec] | None = None
def __init__(self, fn: Callable[..., EventSpec] | None = None, **kwargs):
"""Initialize a CallableEventSpec.
Args:
fn: The function to decorate.
**kwargs: The kwargs to pass to pydantic initializer
"""
if fn is not None:
default_event_spec = fn()
super().__init__(
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)
def __call__(self, *args, **kwargs) -> EventSpec:
"""Call the decorated function.
Args:
*args: The args to pass to the function.
**kwargs: The kwargs to pass to the function.
Returns:
The EventSpec returned from calling the function.
Raises:
EventHandlerTypeError: If the CallableEventSpec has no associated function.
"""
from reflex.utils.exceptions import EventHandlerTypeError
if self.fn is None:
msg = "CallableEventSpec has no associated function."
raise EventHandlerTypeError(msg)
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: Sequence["EventSpec | EventVar | EventCallback"] = dataclasses.field(
default_factory=list
)
args_spec: Callable | Sequence[Callable] | None = dataclasses.field(default=None)
invocation: Var | None = dataclasses.field(default=None)
@classmethod
def create(
cls,
value: "EventType",
args_spec: ArgsSpec | Sequence[ArgsSpec],
key: str | None = None,
**event_chain_kwargs,
) -> "EventChain | Var":
"""Create an event chain from a variety of input types.
Args:
value: The value to create the event chain from.
args_spec: The args_spec of the event trigger being bound.
key: The key of the event trigger being bound.
**event_chain_kwargs: Additional kwargs to pass to the EventChain constructor.
Returns:
The event chain.
Raises:
ValueError: If the value is not a valid event chain.
"""
# If it's an event chain var, return it.
if isinstance(value, Var):
if isinstance(value, EventChainVar):
return value
if isinstance(value, EventVar):
value = [value]
elif safe_issubclass(value._var_type, (EventChain, EventSpec)):
return cls.create(
value=value.guess_type(),
args_spec=args_spec,
key=key,
**event_chain_kwargs,
)
else:
msg = f"Invalid event chain: {value!s} of type {value._var_type}"
raise ValueError(msg)
elif isinstance(value, EventChain):
# Trust that the caller knows what they're doing passing an EventChain directly
return value
# If the input is a single event handler, wrap it in a list.
if isinstance(value, (EventHandler, EventSpec)):
value = [value]
# If the input is a list of event handlers, create an event chain.
if isinstance(value, list):
events: list[EventSpec | EventVar] = []
for v in value:
if isinstance(v, (EventHandler, EventSpec)):
# Call the event handler to get the event.
events.append(call_event_handler(v, args_spec, key=key))
elif isinstance(v, Callable):
# Call the lambda to get the event chain.
result = call_event_fn(v, args_spec, key=key)
if isinstance(result, Var):
msg = (
f"Invalid event chain: {v}. Cannot use a Var-returning "
"lambda inside an EventChain list."
)
raise ValueError(msg)
events.extend(result)
elif isinstance(v, EventVar):
events.append(v)
else:
msg = f"Invalid event: {v}"
raise ValueError(msg)
# If the input is a callable, create an event chain.
elif isinstance(value, Callable):
result = call_event_fn(value, args_spec, key=key)
if isinstance(result, Var):
# Recursively call this function if the lambda returned an EventChain Var.
return cls.create(
value=result, args_spec=args_spec, key=key, **event_chain_kwargs
)
events = [*result]
# Otherwise, raise an error.
else:
msg = f"Invalid event chain: {value}"
raise ValueError(msg)
# Add args to the event specs if necessary.
events = [
(e.with_args(get_handler_args(e)) if isinstance(e, EventSpec) else e)
for e in events
]
# Return the event chain.
return cls(
events=events,
args_spec=args_spec,
**event_chain_kwargs,
)
@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 = ""
checked: bool = False
@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 = ""
altKey: bool = False # noqa: N815
ctrlKey: bool = False # noqa: N815
metaKey: bool = False # noqa: N815
shiftKey: bool = False # noqa: N815
def input_event(e: ObjectVar[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 int_input_event(e: ObjectVar[JavascriptInputEvent]) -> tuple[Var[int]]:
"""Get the value from an input event as an int.
Args:
e: The input event.
Returns:
The value from the input event as an int.
"""
return (Var("Number").to(FunctionVar).call(e.target.value).to(int),)
def float_input_event(e: ObjectVar[JavascriptInputEvent]) -> tuple[Var[float]]:
"""Get the value from an input event as a float.
Args:
e: The input event.
Returns:
The value from the input event as a float.
"""
return (Var("Number").to(FunctionVar).call(e.target.value).to(float),)
def checked_input_event(e: ObjectVar[JavascriptInputEvent]) -> tuple[Var[bool]]:
"""Get the checked state from an input event.
Args:
e: The input event.
Returns:
The checked state from the input event.
"""
return (e.target.checked,)
class KeyInputInfo(TypedDict):
"""Information about a key input event."""
alt_key: bool
ctrl_key: bool
meta_key: bool
shift_key: bool
def key_event(
e: ObjectVar[JavasciptKeyboardEvent],
) -> tuple[Var[str], Var[KeyInputInfo]]:
"""Get the key from a keyboard event.
Args:
e: The keyboard event.
Returns:
The key from the keyboard event.
"""
return (
e.key.to(str),
Var.create(
{
"alt_key": e.altKey,
"ctrl_key": e.ctrlKey,
"meta_key": e.metaKey,
"shift_key": e.shiftKey,
},
).to(KeyInputInfo),
)
@dataclasses.dataclass(
init=True,
frozen=True,
)
class JavascriptMouseEvent:
"""Interface for a Javascript MouseEvent https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent."""
button: int = 0
buttons: list[int] = dataclasses.field(default_factory=list)
clientX: int = 0 # noqa: N815
clientY: int = 0 # noqa: N815
altKey: bool = False # noqa: N815
ctrlKey: bool = False # noqa: N815
metaKey: bool = False # noqa: N815
shiftKey: bool = False # noqa: N815
class JavascriptPointerEvent(JavascriptMouseEvent):
"""Interface for a Javascript PointerEvent https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent.
Inherits from JavascriptMouseEvent.
"""
class MouseEventInfo(TypedDict):
"""Information about a mouse event."""
button: int
buttons: int
client_x: int
client_y: int
alt_key: bool
ctrl_key: bool
meta_key: bool
shift_key: bool
class PointerEventInfo(MouseEventInfo):
"""Information about a pointer event."""
def pointer_event_spec(
e: ObjectVar[JavascriptPointerEvent],
) -> tuple[Var[PointerEventInfo]]:
"""Get the pointer event information.
Args:
e: The pointer event.
Returns:
The pointer event information.
"""
return (
Var.create(
{
"button": e.button,
"buttons": e.buttons,
"client_x": e.clientX,
"client_y": e.clientY,
"alt_key": e.altKey,
"ctrl_key": e.ctrlKey,
"meta_key": e.metaKey,
"shift_key": e.shiftKey,
},
).to(PointerEventInfo),
)
def no_args_event_spec() -> tuple[()]:
"""Empty event handler.
Returns:
An empty tuple.
"""
return ()
T = TypeVar("T")
U = TypeVar("U")
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 passthrough_event_spec( # pyright: ignore [reportOverlappingOverload]
event_type: type[T], /
) -> Callable[[Var[T]], tuple[Var[T]]]: ...
@overload
def passthrough_event_spec(
event_type_1: type[T], event_type2: type[U], /
) -> Callable[[Var[T], Var[U]], tuple[Var[T], Var[U]]]: ...
@overload
def passthrough_event_spec(*event_types: type[T]) -> IdentityEventReturn[T]: ...
def passthrough_event_spec(*event_types: type[T]) -> IdentityEventReturn[T]: # pyright: ignore [reportInconsistentOverload]
"""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]
inner.__signature__ = inspect.signature(inner).replace( # pyright: ignore [reportFunctionMemberAccess]
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: str | None = None
on_upload_progress: EventHandler | Callable | None = None
@staticmethod
def on_upload_progress_args_spec(_prog: Var[dict[str, int | float | bool]]):
"""Args spec for on_upload_progress event handler.
Returns:
The arg mapping passed to backend event handler
"""
return [_prog]
def as_event_spec(self, handler: EventHandler) -> EventSpec:
"""Get the EventSpec for the file upload.
Args:
handler: The event handler.
Returns:
The event spec for the handler.
Raises:
ValueError: If the on_upload_progress is not a valid event handler.
"""
from reflex.components.core.upload import (
DEFAULT_UPLOAD_ID,
upload_files_context_var_data,
)
upload_id = self.upload_id or DEFAULT_UPLOAD_ID
spec_args = [
(
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(_js_expr="upload_id"),
LiteralVar.create(upload_id),
),
]
if self.on_upload_progress is not None:
on_upload_progress = self.on_upload_progress
if isinstance(on_upload_progress, EventHandler):
events = [
call_event_handler(
on_upload_progress,
self.on_upload_progress_args_spec,
),
]
elif isinstance(on_upload_progress, Callable):
# Call the lambda to get the event chain.
events = call_event_fn(
on_upload_progress, self.on_upload_progress_args_spec
)
else:
msg = f"{on_upload_progress} is not a valid event handler."
raise ValueError(msg)
if isinstance(events, Var):
msg = f"{on_upload_progress} cannot return a var {events}."
raise ValueError(msg)
on_upload_progress_chain = EventChain(
events=[*events],
args_spec=self.on_upload_progress_args_spec,
)
formatted_chain = str(format.format_prop(on_upload_progress_chain))
spec_args.append(
(
Var(_js_expr="on_upload_progress"),
FunctionStringVar(
formatted_chain.strip("{}"),
).to(FunctionVar, EventChain),
),
)
return EventSpec(
handler=handler,
client_handler_name="uploadFiles",
args=tuple(spec_args),
event_actions=handler.event_actions.copy(),
)
# Alias for rx.upload_files
upload_files = FileUpload
# Special server-side events.
def server_side(name: str, sig: inspect.Signature, **kwargs) -> EventSpec:
"""A server-side event.
Args:
name: The name of the event.
sig: The function signature of the event.
**kwargs: The arguments to pass to the event.
Returns:
An event spec for a server-side event.
"""
def fn():
return None
fn.__qualname__ = name
fn.__signature__ = sig # pyright: ignore [reportFunctionMemberAccess]
return EventSpec(
handler=EventHandler(fn=fn, state_full_name=FRONTEND_EVENT_STATE),
args=tuple(
(
Var(_js_expr=k),
LiteralVar.create(v),
)
for k, v in kwargs.items()
),
)
def redirect(
path: str | Var[str],
is_external: bool = False,
replace: bool = False,
) -> EventSpec:
"""Redirect to a new path.
Args:
path: The path to redirect to.
is_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=is_external,
replace=replace,
)
def console_log(message: str | Var[str]) -> EventSpec:
"""Do a console.log on the browser.
Args:
message: The message to log.
Returns:
An event to log the message.
"""
return run_script(Var("console").to(dict).log.to(FunctionVar).call(message))
@once
def noop() -> EventSpec:
"""Do nothing.
Returns:
An event to do nothing.
"""
return run_script(Var.create(None))
def back() -> EventSpec:
"""Do a history.back on the browser.
Returns:
An event to go back one page.
"""
return run_script(
Var("window").to(dict).history.to(dict).back.to(FunctionVar).call()
)
def window_alert(message: str | Var[str]) -> EventSpec: