-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathcomponent.py
More file actions
2945 lines (2399 loc) ยท 96.2 KB
/
component.py
File metadata and controls
2945 lines (2399 loc) ยท 96.2 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
"""Base component definitions."""
from __future__ import annotations
import contextlib
import copy
import dataclasses
import functools
import inspect
import sys
import typing
from abc import ABC, ABCMeta, abstractmethod
from collections.abc import Callable, Iterator, Mapping, Sequence
from dataclasses import _MISSING_TYPE, MISSING
from functools import wraps
from hashlib import md5
from types import SimpleNamespace
from typing import (
TYPE_CHECKING,
Annotated,
Any,
ClassVar,
ForwardRef,
Generic,
TypeVar,
_eval_type, # pyright: ignore [reportAttributeAccessIssue]
cast,
get_args,
get_origin,
)
from rich.markup import escape
from typing_extensions import dataclass_transform
import reflex.state
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,
EventTriggers,
Hooks,
Imports,
MemoizationDisposition,
MemoizationMode,
PageNames,
)
from reflex.constants.compiler import SpecialAttributes
from reflex.constants.state import FRONTEND_EVENT_STATE
from reflex.event import (
EventCallback,
EventChain,
EventHandler,
EventSpec,
no_args_event_spec,
parse_args_spec,
run_script,
unwrap_var_annotation,
)
from reflex.style import Style, format_as_emotion
from reflex.utils import console, format, imports, types
from reflex.utils.imports import ImportDict, ImportVar, ParsedImportDict, parse_imports
from reflex.vars import VarData
from reflex.vars.base import (
CachedVarOperation,
LiteralNoneVar,
LiteralVar,
Var,
cached_property_no_lock,
)
from reflex.vars.function import ArgsFunctionOperation, FunctionStringVar, FunctionVar
from reflex.vars.number import ternary_operation
from reflex.vars.object import ObjectVar
from reflex.vars.sequence import LiteralArrayVar, LiteralStringVar, StringVar
def resolve_annotations(
raw_annotations: Mapping[str, type[Any]], module_name: str | None
) -> dict[str, type[Any]]:
"""Partially taken from typing.get_type_hints.
Resolve string or ForwardRef annotations into type objects if possible.
Args:
raw_annotations: The raw annotations to resolve.
module_name: The name of the module.
Returns:
The resolved annotations.
"""
module = sys.modules.get(module_name, None) if module_name is not None else None
base_globals: dict[str, Any] | None = (
module.__dict__ if module is not None else None
)
annotations = {}
for name, value in raw_annotations.items():
if isinstance(value, str):
if sys.version_info == (3, 10, 0):
value = ForwardRef(value, is_argument=False)
else:
value = ForwardRef(value, is_argument=False, is_class=True)
try:
if sys.version_info >= (3, 13):
value = _eval_type(value, base_globals, None, type_params=())
else:
value = _eval_type(value, base_globals, None)
except NameError:
# this is ok, it can be fixed with update_forward_refs
pass
annotations[name] = value
return annotations
FIELD_TYPE = TypeVar("FIELD_TYPE")
class ComponentField(Generic[FIELD_TYPE]):
"""A field for a component."""
def __init__(
self,
default: FIELD_TYPE | _MISSING_TYPE = MISSING,
default_factory: Callable[[], FIELD_TYPE] | None = None,
is_javascript: bool | None = None,
annotated_type: type[Any] | _MISSING_TYPE = MISSING,
) -> None:
"""Initialize the field.
Args:
default: The default value for the field.
default_factory: The default factory for the field.
is_javascript: Whether the field is a javascript property.
annotated_type: The annotated type for the field.
"""
self.default = default
self.default_factory = default_factory
self.is_javascript = is_javascript
self.outer_type_ = self.annotated_type = annotated_type
type_origin = get_origin(annotated_type) or annotated_type
if type_origin is Annotated:
type_origin = annotated_type.__origin__ # pyright: ignore [reportAttributeAccessIssue]
self.type_ = self.type_origin = type_origin
def default_value(self) -> FIELD_TYPE:
"""Get the default value for the field.
Returns:
The default value for the field.
Raises:
ValueError: If no default value or factory is provided.
"""
if self.default is not MISSING:
return self.default
if self.default_factory is not None:
return self.default_factory()
raise ValueError("No default value or factory provided.")
def __repr__(self) -> str:
"""Represent the field in a readable format.
Returns:
The string representation of the field.
"""
annotated_type_str = (
f", annotated_type={self.annotated_type!r}"
if self.annotated_type is not MISSING
else ""
)
if self.default is not MISSING:
return f"ComponentField(default={self.default!r}, is_javascript={self.is_javascript!r}{annotated_type_str})"
return f"ComponentField(default_factory={self.default_factory!r}, is_javascript={self.is_javascript!r}{annotated_type_str})"
def field(
default: FIELD_TYPE | _MISSING_TYPE = MISSING,
default_factory: Callable[[], FIELD_TYPE] | None = None,
is_javascript_property: bool | None = None,
) -> FIELD_TYPE:
"""Create a field for a component.
Args:
default: The default value for the field.
default_factory: The default factory for the field.
is_javascript_property: Whether the field is a javascript property.
Returns:
The field for the component.
Raises:
ValueError: If both default and default_factory are specified.
"""
if default is not MISSING and default_factory is not None:
raise ValueError("cannot specify both default and default_factory")
return ComponentField( # pyright: ignore [reportReturnType]
default=default,
default_factory=default_factory,
is_javascript=is_javascript_property,
)
@dataclass_transform(kw_only_default=True, field_specifiers=(field,))
class BaseComponentMeta(ABCMeta):
"""Meta class for BaseComponent."""
if TYPE_CHECKING:
_inherited_fields: Mapping[str, ComponentField]
_own_fields: Mapping[str, ComponentField]
_fields: Mapping[str, ComponentField]
_js_fields: Mapping[str, ComponentField]
def __new__(cls, name: str, bases: tuple[type], namespace: dict[str, Any]) -> type:
"""Create a new class.
Args:
name: The name of the class.
bases: The bases of the class.
namespace: The namespace of the class.
Returns:
The new class.
"""
# Add the field to the class
inherited_fields: dict[str, ComponentField] = {}
own_fields: dict[str, ComponentField] = {}
resolved_annotations = resolve_annotations(
namespace.get("__annotations__", {}), namespace["__module__"]
)
for base in bases[::-1]:
if hasattr(base, "_inherited_fields"):
inherited_fields.update(base._inherited_fields)
for base in bases[::-1]:
if hasattr(base, "_own_fields"):
inherited_fields.update(base._own_fields)
for key, value, inherited_field in [
(key, value, inherited_field)
for key, value in namespace.items()
if key not in resolved_annotations
and ((inherited_field := inherited_fields.get(key)) is not None)
]:
new_value = ComponentField(
default=value,
is_javascript=inherited_field.is_javascript,
annotated_type=inherited_field.annotated_type,
)
own_fields[key] = new_value
for key, annotation in resolved_annotations.items():
value = namespace.get(key, MISSING)
if types.is_classvar(annotation):
# If the annotation is a classvar, skip it.
continue
if value is MISSING:
value = ComponentField(
default=None,
is_javascript=(key[0] != "_"),
annotated_type=annotation,
)
elif not isinstance(value, ComponentField):
value = ComponentField(
default=value,
is_javascript=(
(key[0] != "_")
if (existing_field := inherited_fields.get(key)) is None
else existing_field.is_javascript
),
annotated_type=annotation,
)
else:
value = ComponentField(
default=value.default,
default_factory=value.default_factory,
is_javascript=value.is_javascript,
annotated_type=annotation,
)
own_fields[key] = value
namespace["_own_fields"] = own_fields
namespace["_inherited_fields"] = inherited_fields
all_fields = inherited_fields | own_fields
namespace["_fields"] = all_fields
namespace["_js_fields"] = {
key: value
for key, value in all_fields.items()
if value.is_javascript is True
}
return super().__new__(cls, name, bases, namespace)
class BaseComponent(metaclass=BaseComponentMeta):
"""The base class for all Reflex components.
This is something that can be rendered as a Component via the Reflex compiler.
"""
# The children nested within the component.
children: list[BaseComponent] = field(
default_factory=list, is_javascript_property=False
)
# The library that the component is based on.
library: str | None = field(default=None, is_javascript_property=False)
# List here the non-react dependency needed by `library`
lib_dependencies: list[str] = field(
default_factory=list, is_javascript_property=False
)
# List here the dependencies that need to be transpiled by Next.js
transpile_packages: list[str] = field(
default_factory=list, is_javascript_property=False
)
# The tag to use when rendering the component.
tag: str | None = field(default=None, is_javascript_property=False)
def __init__(
self,
**kwargs,
):
"""Initialize the component.
Args:
**kwargs: The kwargs to pass to the component.
"""
for key, value in kwargs.items():
setattr(self, key, value)
for name, value in self.get_fields().items():
if name not in kwargs:
setattr(self, name, value.default_value())
def set(self, **kwargs):
"""Set the component props.
Args:
**kwargs: The kwargs to set.
Returns:
The component with the updated props.
"""
for key, value in kwargs.items():
setattr(self, key, value)
return self
def __eq__(self, value: Any) -> bool:
"""Check if the component is equal to another value.
Args:
value: The value to compare to.
Returns:
Whether the component is equal to the value.
"""
return type(self) is type(value) and bool(
getattr(self, key) == getattr(value, key) for key in self.get_fields()
)
@classmethod
def get_fields(cls) -> Mapping[str, ComponentField]:
"""Get the fields of the component.
Returns:
The fields of the component.
"""
return cls._fields
@classmethod
def get_js_fields(cls) -> Mapping[str, ComponentField]:
"""Get the javascript fields of the component.
Returns:
The javascript fields of the component.
"""
return cls._js_fields
@abstractmethod
def render(self) -> dict:
"""Render the component.
Returns:
The dictionary for template of the component.
"""
@abstractmethod
def _get_all_hooks_internal(self) -> dict[str, VarData | None]:
"""Get the reflex internal hooks for the component and its children.
Returns:
The code that should appear just before user-defined hooks.
"""
@abstractmethod
def _get_all_hooks(self) -> dict[str, VarData | None]:
"""Get the React hooks for this component.
Returns:
The code that should appear just before returning the rendered component.
"""
@abstractmethod
def _get_all_imports(self) -> ParsedImportDict:
"""Get all the libraries and fields that are used by the component.
Returns:
The import dict with the required imports.
"""
@abstractmethod
def _get_all_dynamic_imports(self) -> set[str]:
"""Get dynamic imports for the component.
Returns:
The dynamic imports.
"""
@abstractmethod
def _get_all_custom_code(self) -> set[str]:
"""Get custom code for the component.
Returns:
The custom code.
"""
@abstractmethod
def _get_all_refs(self) -> set[str]:
"""Get the refs for the children of the component.
Returns:
The refs for the children.
"""
class ComponentNamespace(SimpleNamespace):
"""A namespace to manage components with subcomponents."""
def __hash__(self) -> int: # pyright: ignore [reportIncompatibleVariableOverride]
"""Get the hash of the namespace.
Returns:
The hash of the namespace.
"""
return hash(type(self).__name__)
def evaluate_style_namespaces(style: ComponentStyle) -> dict:
"""Evaluate namespaces in the style.
Args:
style: The style to evaluate.
Returns:
The evaluated style.
"""
return {
k.__call__ if isinstance(k, ComponentNamespace) else k: v
for k, v in style.items()
}
# Map from component to styling.
ComponentStyle = dict[str | type[BaseComponent] | Callable | ComponentNamespace, Any]
ComponentChild = types.PrimitiveType | Var | BaseComponent
ComponentChildTypes = (*types.PrimitiveTypes, Var, BaseComponent, type(None))
def _satisfies_type_hint(obj: Any, type_hint: Any) -> bool:
return types._isinstance(
obj,
type_hint,
nested=1,
treat_var_as_type=True,
treat_mutable_obj_as_immutable=(
isinstance(obj, Var) and not isinstance(obj, LiteralVar)
),
)
def satisfies_type_hint(obj: Any, type_hint: Any) -> bool:
"""Check if an object satisfies a type hint.
Args:
obj: The object to check.
type_hint: The type hint to check against.
Returns:
Whether the object satisfies the type hint.
"""
if _satisfies_type_hint(obj, type_hint):
return True
if _satisfies_type_hint(obj, type_hint | None):
obj = (
obj
if not isinstance(obj, Var)
else (obj._var_value if isinstance(obj, LiteralVar) else obj)
)
console.deprecate(
"implicit-none-for-component-fields",
reason="Passing Vars with possible None values to component fields not explicitly marked as Optional is deprecated. "
+ f"Passed {obj!s} of type {escape(str(type(obj) if not isinstance(obj, Var) else obj._var_type))} to {escape(str(type_hint))}.",
deprecation_version="0.7.2",
removal_version="0.8.0",
)
return True
return False
def _components_from(
component_or_var: BaseComponent | Var,
) -> tuple[BaseComponent, ...]:
"""Get the components from a component or Var.
Args:
component_or_var: The component or Var to get the components from.
Returns:
The components.
"""
if isinstance(component_or_var, Var):
var_data = component_or_var._get_all_var_data()
return var_data.components if var_data else ()
if isinstance(component_or_var, BaseComponent):
return (component_or_var,)
return ()
DEFAULT_TRIGGERS: dict[str, types.ArgsSpec | Sequence[types.ArgsSpec]] = {
EventTriggers.ON_FOCUS: no_args_event_spec,
EventTriggers.ON_BLUR: no_args_event_spec,
EventTriggers.ON_CLICK: no_args_event_spec,
EventTriggers.ON_CONTEXT_MENU: no_args_event_spec,
EventTriggers.ON_DOUBLE_CLICK: no_args_event_spec,
EventTriggers.ON_MOUSE_DOWN: no_args_event_spec,
EventTriggers.ON_MOUSE_ENTER: no_args_event_spec,
EventTriggers.ON_MOUSE_LEAVE: no_args_event_spec,
EventTriggers.ON_MOUSE_MOVE: no_args_event_spec,
EventTriggers.ON_MOUSE_OUT: no_args_event_spec,
EventTriggers.ON_MOUSE_OVER: no_args_event_spec,
EventTriggers.ON_MOUSE_UP: no_args_event_spec,
EventTriggers.ON_SCROLL: no_args_event_spec,
EventTriggers.ON_MOUNT: no_args_event_spec,
EventTriggers.ON_UNMOUNT: no_args_event_spec,
}
T = TypeVar("T", bound="Component")
class Component(BaseComponent, ABC):
"""A component with style, event trigger and other props."""
# The style of the component.
style: Style = field(default_factory=Style, is_javascript_property=False)
# A mapping from event triggers to event chains.
event_triggers: dict[str, EventChain | Var] = field(
default_factory=dict, is_javascript_property=False
)
# The alias for the tag.
alias: str | None = field(default=None, is_javascript_property=False)
# Whether the component is a global scope tag. True for tags like `html`, `head`, `body`.
_is_tag_in_global_scope: ClassVar[bool] = False
# Whether the import is default or named.
is_default: bool | None = field(default=False, is_javascript_property=False)
# A unique key for the component.
key: Any = field(default=None, is_javascript_property=False)
# The id for the component.
id: Any = field(default=None, is_javascript_property=False)
# The Var to pass as the ref to the component.
ref: Var | None = field(default=None, is_javascript_property=False)
# The class name for the component.
class_name: Any = field(default=None, is_javascript_property=False)
# Special component props.
special_props: list[Var] = field(default_factory=list, is_javascript_property=False)
# Whether the component should take the focus once the page is loaded
autofocus: bool = field(default=False, is_javascript_property=False)
# components that cannot be children
_invalid_children: ClassVar[list[str]] = []
# only components that are allowed as children
_valid_children: ClassVar[list[str]] = []
# only components that are allowed as parent
_valid_parents: ClassVar[list[str]] = []
# props to change the name of
_rename_props: ClassVar[dict[str, str]] = {}
# custom attribute
custom_attrs: dict[str, Var | Any] = field(
default_factory=dict, is_javascript_property=False
)
# When to memoize this component and its children.
_memoization_mode: MemoizationMode = field(
default_factory=MemoizationMode, is_javascript_property=False
)
# State class associated with this component instance
State: type[reflex.state.State] | None = field(
default=None, is_javascript_property=False
)
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.
Implementations do NOT need to call super(). The result of calling
add_imports in each parent class will be merged internally.
Returns:
The additional imports for this component subclass.
The format of the return value is a dictionary where the keys are the
library names (with optional npm-style version specifications) mapping
to a single name to be imported, or a list names to be imported.
For advanced use cases, the values can be ImportVar instances (for
example, to provide an alias or mark that an import is the default
export from the given library).
```python
return {
"react": "useEffect",
"react-draggable": ["DraggableCore", rx.ImportVar(tag="Draggable", is_default=True)],
}
```
"""
return {}
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
React component function.
Each logical hook should be a separate string in the list.
Common strings will be deduplicated and inserted into the component
function only once, so define const variables and other identical code
in their own strings to avoid defining the same const or hook multiple
times.
If a hook depends on specific data from the component instance, be sure
to use unique values inside the string to _avoid_ deduplication.
Implementations do NOT need to call super(). The result of calling
add_hooks in each parent class will be merged and deduplicated internally.
Returns:
The additional hooks for this component subclass.
```python
return [
"const [count, setCount] = useState(0);",
"useEffect(() => { setCount((prev) => prev + 1); console.log(`mounted ${count} times`); }, []);",
]
```
"""
return []
def add_custom_code(self) -> list[str]:
"""Add custom Javascript code into the page that contains this component.
Custom code is inserted at module level, after any imports.
Each string of custom code is deduplicated per-page, so take care to
avoid defining the same const or function differently from different
component instances.
Custom code is useful for defining global functions or constants which
can then be referenced inside hooks or used by component vars.
Implementations do NOT need to call super(). The result of calling
add_custom_code in each parent class will be merged and deduplicated internally.
Returns:
The additional custom code for this component subclass.
```python
return [
"const translatePoints = (event) => { return { x: event.clientX, y: event.clientY }; };",
]
```
"""
return []
@classmethod
def __init_subclass__(cls, **kwargs):
"""Set default properties.
Args:
**kwargs: The kwargs to pass to the superclass.
"""
super().__init_subclass__(**kwargs)
# Ensure renamed props from parent classes are applied to the subclass.
if cls._rename_props:
inherited_rename_props = {}
for parent in reversed(cls.mro()):
if issubclass(parent, Component) and parent._rename_props:
inherited_rename_props.update(parent._rename_props)
cls._rename_props = inherited_rename_props
def __init__(self, **kwargs):
"""Initialize the custom component.
Args:
**kwargs: The kwargs to pass to the component.
"""
super().__init__(
children=kwargs.get("children", []),
)
console.deprecate(
"component-direct-instantiation",
reason="Use the `create` method instead.",
deprecation_version="0.7.2",
removal_version="0.8.0",
)
self._post_init(**kwargs)
def _post_init(self, *args, **kwargs):
"""Initialize the component.
Args:
*args: Args to initialize the component.
**kwargs: Kwargs to initialize the component.
Raises:
TypeError: If an invalid prop is passed.
ValueError: If an event trigger passed is not valid.
"""
# Set the id and children initially.
children = kwargs.get("children", [])
self._validate_component_children(children)
# Get the component fields, triggers, and props.
fields = self.get_fields()
component_specific_triggers = self.get_event_triggers()
props = self.get_props()
# Add any events triggers.
if "event_triggers" not in kwargs:
kwargs["event_triggers"] = {}
kwargs["event_triggers"] = kwargs["event_triggers"].copy()
# Iterate through the kwargs and set the props.
for key, value in kwargs.items():
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/guide/#event-triggers for more info."
)
if key in component_specific_triggers:
# Event triggers are bound to event chains.
is_var = False
elif key in props:
# Set the field type.
is_var = (
field.type_origin is Var if (field := fields.get(key)) else False
)
else:
continue
# Check whether the key is a component prop.
if is_var:
try:
kwargs[key] = LiteralVar.create(value)
# Get the passed type and the var type.
passed_type = kwargs[key]._var_type
expected_type = types.get_args(
types.get_field_type(type(self), key)
)[0]
except TypeError:
# If it is not a valid var, check the base types.
passed_type = type(value)
expected_type = types.get_field_type(type(self), key)
if not satisfies_type_hint(value, expected_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 component_specific_triggers:
kwargs["event_triggers"][key] = EventChain.create(
value=value,
args_spec=component_specific_triggers[key],
key=key,
)
# Remove any keys that were added as events.
for key in kwargs["event_triggers"]:
kwargs.pop(key, None)
# Place data_ and aria_ attributes into custom_attrs
special_attributes = [
key
for key in kwargs
if key not in fields and SpecialAttributes.is_special(key)
]
if special_attributes:
custom_attrs = kwargs.setdefault("custom_attrs", {})
custom_attrs.update(
{
format.to_kebab_case(key): kwargs.pop(key)
for key in special_attributes
}
)
# Add style props to the component.
style = kwargs.get("style", {})
if isinstance(style, Sequence):
if any(not isinstance(s, Mapping) for s in style):
raise TypeError("Style must be a dictionary or a list of dictionaries.")
# Merge styles, the later ones overriding keys in the earlier ones.
style = {
k: v
for style_dict in style
for k, v in cast(Mapping, 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,
}
fields_style = self.get_fields()["style"]
kwargs["style"] = Style(
{
**fields_style.default_value(),
**style,
**{attr: value for attr, value in kwargs.items() if attr not in fields},
}
)
# Convert class_name to str if it's list
class_name = kwargs.get("class_name", "")
if isinstance(class_name, (list, tuple)):
has_var = False
for c in class_name:
if isinstance(c, str):
continue
if isinstance(c, Var):
if not isinstance(c, StringVar) and not issubclass(
c._var_type, str
):
raise TypeError(
f"Invalid class_name passed for prop {type(self).__name__}.class_name, expected type str, got value {c._js_expr} of type {c._var_type}."
)
has_var = True
else:
raise TypeError(
f"Invalid class_name passed for prop {type(self).__name__}.class_name, expected type str, got value {c} of type {type(c)}."
)
if has_var:
kwargs["class_name"] = LiteralArrayVar.create(
class_name, _var_type=list[str]
).join(" ")
else:
kwargs["class_name"] = " ".join(class_name)
elif (
isinstance(class_name, Var)
and not isinstance(class_name, StringVar)
and not issubclass(class_name._var_type, str)
):
raise TypeError(
f"Invalid class_name passed for prop {type(self).__name__}.class_name, expected type str, got value {class_name._js_expr} of type {class_name._var_type}."
)
# Construct the component.
for key, value in kwargs.items():
setattr(self, key, value)
def get_event_triggers(
self,
) -> dict[str, types.ArgsSpec | Sequence[types.ArgsSpec]]:
"""Get the event triggers for the component.
Returns:
The event triggers.
"""
# Look for component specific triggers,
# e.g. variable declared as EventHandler types.
return DEFAULT_TRIGGERS | {
name: (
metadata[0]
if (
(metadata := getattr(field.annotated_type, "__metadata__", None))
is not None
)
else no_args_event_spec
)
for name, field in self.get_fields().items()
if field.type_origin is EventHandler
}
def __repr__(self) -> str:
"""Represent the component in React.
Returns:
The code to render the component.
"""
return format.json_dumps(self.render())
def __str__(self) -> str:
"""Represent the component in React.
Returns:
The code to render the component.
"""
from reflex.compiler.compiler import _compile_component
return _compile_component(self)
def _exclude_props(self) -> list[str]:
"""Props to exclude when adding the component props to the Tag.
Returns:
A list of component props to exclude.
"""
return []
def _render(self, props: dict[str, Any] | None = None) -> Tag:
"""Define how to render the component in React.
Args:
props: The props to render (if None, then use get_props).
Returns:
The tag to render.
"""
# Create the base tag.
name = (self.tag if not self.alias else self.alias) or ""
if self._is_tag_in_global_scope and self.library is None:
name = '"' + name + '"'
# Create the base tag.
tag = Tag(
name=name,
special_props=self.special_props,
)
if props is None:
# Add component props to the tag.
props = {
attr.removesuffix("_"): getattr(self, attr) for attr in self.get_props()
}
# Add ref to element if `ref` is None and `id` is not None.
if self.ref is not None:
props["ref"] = self.ref
elif (ref := self.get_ref()) is not None:
props["ref"] = Var(_js_expr=ref)
else:
props = props.copy()
props.update(
**{
trigger: handler
for trigger, handler in self.event_triggers.items()
if trigger not in {EventTriggers.ON_MOUNT, EventTriggers.ON_UNMOUNT}
},
key=self.key,
id=self.id,
class_name=self.class_name,