-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathcomponent.py
More file actions
2764 lines (2278 loc) ยท 91.9 KB
/
component.py
File metadata and controls
2764 lines (2278 loc) ยท 91.9 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 dataclasses
import enum
import functools
import inspect
import operator
import typing
from abc import ABC, ABCMeta, abstractmethod
from collections.abc import Callable, Iterable, 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, Any, ClassVar, TypeVar, cast, get_args, get_origin
from rich.markup import escape
from typing_extensions import Self, dataclass_transform
from reflex_base import constants
from reflex_base.breakpoints import Breakpoints
from reflex_base.components.dynamic import load_dynamic_serializer
from reflex_base.components.field import BaseField, FieldBasedMeta
from reflex_base.components.tags import Tag
from reflex_base.constants import Dirs, EventTriggers, Hooks, Imports, MemoizationMode
from reflex_base.constants.compiler import SpecialAttributes
from reflex_base.constants.state import CAMEL_CASE_MEMO_MARKER
from reflex_base.event import (
EventCallback,
EventChain,
EventHandler,
EventSpec,
args_specs_from_fields,
no_args_event_spec,
parse_args_spec,
pointer_event_spec,
run_script,
unwrap_var_annotation,
)
from reflex_base.style import Style, format_as_emotion
from reflex_base.utils import console, format, imports, types
from reflex_base.utils.imports import ImportDict, ImportVar, ParsedImportDict
from reflex_base.vars import VarData
from reflex_base.vars.base import (
CachedVarOperation,
LiteralNoneVar,
LiteralVar,
Var,
cached_property_no_lock,
)
from reflex_base.vars.function import (
ArgsFunctionOperation,
FunctionStringVar,
FunctionVar,
)
from reflex_base.vars.number import ternary_operation
from reflex_base.vars.object import ObjectVar
from reflex_base.vars.sequence import LiteralArrayVar, LiteralStringVar, StringVar
if TYPE_CHECKING:
import reflex.state
FIELD_TYPE = TypeVar("FIELD_TYPE")
class ComponentField(BaseField[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,
doc: str | None = None,
) -> 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.
doc: Documentation string for the field.
"""
super().__init__(default, default_factory, annotated_type)
self.doc = doc
self.is_javascript = is_javascript
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,
doc: str | 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.
doc: Documentation string for the field.
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:
msg = "cannot specify both default and default_factory"
raise ValueError(msg)
return ComponentField( # pyright: ignore [reportReturnType]
default=default,
default_factory=default_factory,
is_javascript=is_javascript_property,
doc=doc,
)
@dataclass_transform(kw_only_default=True, field_specifiers=(field,))
class BaseComponentMeta(FieldBasedMeta, 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]
@classmethod
def _process_annotated_fields(
cls,
namespace: dict[str, Any],
annotations: dict[str, Any],
inherited_fields: dict[str, ComponentField],
) -> dict[str, ComponentField]:
own_fields: dict[str, ComponentField] = {}
for key, annotation in 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:
is_js = value.is_javascript
if is_js is None:
if (existing_field := inherited_fields.get(key)) is not None:
is_js = existing_field.is_javascript
else:
is_js = key[0] != "_"
default = value.default
# If no default or factory provided, default to None
# (same behavior as bare annotations without field())
if default is MISSING and value.default_factory is None:
default = None
value = ComponentField(
default=default,
default_factory=value.default_factory,
is_javascript=is_js,
annotated_type=annotation,
doc=value.doc,
)
own_fields[key] = value
return own_fields
@classmethod
def _create_field(
cls,
annotated_type: Any,
default: Any = MISSING,
default_factory: Callable[[], Any] | None = None,
) -> ComponentField:
return ComponentField(
annotated_type=annotated_type,
default=default,
default_factory=default_factory,
is_javascript=True, # Default for components
)
@classmethod
def _process_field_overrides(
cls,
namespace: dict[str, Any],
annotations: dict[str, Any],
inherited_fields: dict[str, Any],
) -> dict[str, ComponentField]:
own_fields: dict[str, ComponentField] = {}
for key, value, inherited_field in [
(key, value, inherited_field)
for key, value in namespace.items()
if key not in annotations
and ((inherited_field := inherited_fields.get(key)) is not None)
]:
new_field = ComponentField(
default=value,
is_javascript=inherited_field.is_javascript,
annotated_type=inherited_field.annotated_type,
)
own_fields[key] = new_field
return own_fields
@classmethod
def _finalize_fields(
cls,
namespace: dict[str, Any],
inherited_fields: dict[str, ComponentField],
own_fields: dict[str, ComponentField],
) -> None:
# Call parent implementation
super()._finalize_fields(namespace, inherited_fields, own_fields)
# Add JavaScript fields mapping
all_fields = namespace["_fields"]
namespace["_js_fields"] = {
key: value
for key, value in all_fields.items()
if value.is_javascript is True
}
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.
"""
_frozen: ClassVar[bool] = False
# Render-path caches; allowed to be written even on frozen instances.
_CACHE_ATTRS: ClassVar[frozenset[str]] = frozenset({
"_cached_render_result",
"_vars_cache",
"_imports_cache",
"_hooks_internal_cache",
"_get_component_prop_property",
})
children: tuple[BaseComponent, ...] = field(
doc="The children nested within the component.",
default_factory=tuple,
is_javascript_property=False,
)
# The library that the component is based on.
library: str | None = field(default=None, is_javascript_property=False)
lib_dependencies: list[str] = field(
doc="List here the non-react dependency needed by `library`",
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.
"""
if "children" in kwargs:
kwargs["children"] = tuple(kwargs["children"])
# Bypass ``__setattr__``'s freeze guard: a brand-new instance can't be
# frozen, so the per-attribute check is pure overhead during init.
d = vars(self)
d.update(kwargs)
for name, value in self.get_fields().items():
if name not in kwargs:
d[name] = value.default_value()
def __setattr__(self, key: str, value: Any) -> None:
"""Block writes to frozen components, except for cache attributes.
Args:
key: The attribute name.
value: The attribute value.
Raises:
AttributeError: If the component is frozen and the attribute is not a cache.
"""
if self.__dict__.get("_frozen", False) and key not in type(self)._CACHE_ATTRS:
msg = (
f"Cannot set {key!r} on frozen {type(self).__name__}; "
"use copy_with() to create a modified copy."
)
raise AttributeError(msg)
super().__setattr__(key, value)
def _freeze(self) -> None:
"""Mark this component as frozen.
Subsequent attribute writes outside the cache allowlist will raise.
"""
object.__setattr__(self, "_frozen", True)
def copy_with(self, **updates: Any) -> Self:
"""Return a frozen shallow copy with updated fields.
Bypasses ``__setattr__`` for speed and to skip the freeze guard.
Render-path caches are dropped because they may depend on the fields
being replaced.
Args:
**updates: Field values to override on the copy.
Returns:
A new frozen instance with the requested updates applied.
"""
new = self.__class__.__new__(self.__class__)
d = vars(new)
d.update(vars(self))
for cache_attr in type(self)._CACHE_ATTRS:
d.pop(cache_attr, None)
if "children" in updates:
updates["children"] = tuple(updates["children"])
d.update(updates)
d["_frozen"] = True
return new
def set(self, **kwargs):
"""Set the component props, returning a new frozen instance.
Args:
**kwargs: The kwargs to set.
Returns:
A new component with the updated props.
"""
return self.copy_with(**kwargs)
def __copy__(self) -> BaseComponent:
"""Return a shallow copy suitable for compile-time mutation.
Bypasses ``copy.copy``'s generic ``__reduce_ex__`` dispatch. Nested
mutable containers (``children``, ``style``, ``event_triggers``) are
shared with the original until the caller explicitly rebinds them.
Render-path caches populated on the original are dropped so the clone
recomputes against its (potentially rebound) fields.
Returns:
A new instance of the same class with ``__dict__`` shallow-copied.
"""
new = self.__class__.__new__(self.__class__)
new_dict = vars(new)
new_dict.update(vars(self))
for attr in type(self)._CACHE_ATTRS:
new_dict.pop(attr, None)
return new
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) -> dict[str, None]:
"""Get custom code for the component.
Returns:
The custom code.
"""
@abstractmethod
def _get_all_refs(self) -> dict[str, None]:
"""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]
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.warn(
"Passing None to a Var that is not explicitly marked as Optional (| None) 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))}."
)
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 ()
def _hash_str(value: str) -> str:
return md5(f'"{value}"'.encode(), usedforsecurity=False).hexdigest()
def _update_deterministic_hash(hasher: Any, value: object) -> None:
"""Feed ``value`` into ``hasher`` using a self-delimiting, type-tagged encoding.
Each branch writes a distinct type tag plus length-prefixed payload, which
keeps the encoding injective without building intermediate strings โ the
nested ``str([...])`` approach this replaces was the dominant cost of
``_deterministic_hash`` (~4x speedup on synthetic, ~2x on real renders).
Args:
hasher: A ``hashlib`` hasher (must accept ``.update(bytes)``).
value: The value to fold into the hasher.
Raises:
TypeError: If the value is not hashable.
"""
if value is None:
hasher.update(b"N")
elif isinstance(value, bool):
hasher.update(b"T" if value else b"F")
elif isinstance(value, (int, float, enum.Enum)):
hasher.update(b"n")
hasher.update(str(value).encode())
elif isinstance(value, str):
encoded = value.encode()
hasher.update(b"s")
hasher.update(len(encoded).to_bytes(8, "little"))
hasher.update(encoded)
elif isinstance(value, dict):
items = sorted(value.items(), key=operator.itemgetter(0))
hasher.update(b"d")
hasher.update(len(items).to_bytes(8, "little"))
for k, v in items:
_update_deterministic_hash(hasher, k)
_update_deterministic_hash(hasher, v)
elif isinstance(value, (tuple, list)):
hasher.update(b"l")
hasher.update(len(value).to_bytes(8, "little"))
for item in value:
_update_deterministic_hash(hasher, item)
elif isinstance(value, Var):
hasher.update(b"v")
_update_deterministic_hash(hasher, value._js_expr)
_update_deterministic_hash(hasher, value._get_all_var_data())
elif dataclasses.is_dataclass(value):
fields = dataclasses.fields(value)
hasher.update(b"D")
hasher.update(len(fields).to_bytes(8, "little"))
for field in fields:
hasher.update(field.name.encode())
_update_deterministic_hash(hasher, getattr(value, field.name))
elif isinstance(value, BaseComponent):
hasher.update(b"C")
_update_deterministic_hash(hasher, value.render())
else:
msg = (
f"Cannot hash value `{value}` of type `{type(value).__name__}`. "
"Only BaseComponent, Var, VarData, dict, str, tuple, and enum.Enum are supported."
)
raise TypeError(msg)
def _deterministic_hash(value: object) -> str:
"""Hash a rendered dictionary.
Args:
value: The dictionary to hash.
Returns:
The hash of the dictionary.
Raises:
TypeError: If the value is not hashable.
"""
hasher = md5(usedforsecurity=False)
_update_deterministic_hash(hasher, value)
return hasher.hexdigest()
@dataclasses.dataclass(kw_only=True, frozen=True, slots=True)
class TriggerDefinition:
"""A default event trigger with its args spec and description."""
spec: types.ArgsSpec | Sequence[types.ArgsSpec]
description: str
DEFAULT_TRIGGERS_AND_DESC: Mapping[str, TriggerDefinition] = {
EventTriggers.ON_FOCUS: TriggerDefinition(
spec=no_args_event_spec,
description="Fired when the element (or some element inside of it) receives focus. For example, it is called when the user clicks on a text input.",
),
EventTriggers.ON_BLUR: TriggerDefinition(
spec=no_args_event_spec,
description="Fired when focus has left the element (or left some element inside of it). For example, it is called when the user clicks outside of a focused text input.",
),
EventTriggers.ON_CLICK: TriggerDefinition(
spec=pointer_event_spec, # pyright: ignore [reportArgumentType]
description="Fired when the user clicks on an element. For example, it's called when the user clicks on a button.",
),
EventTriggers.ON_CONTEXT_MENU: TriggerDefinition(
spec=pointer_event_spec, # pyright: ignore [reportArgumentType]
description="Fired when the user right-clicks on an element.",
),
EventTriggers.ON_DOUBLE_CLICK: TriggerDefinition(
spec=pointer_event_spec, # pyright: ignore [reportArgumentType]
description="Fired when the user double-clicks on an element.",
),
EventTriggers.ON_MOUSE_DOWN: TriggerDefinition(
spec=no_args_event_spec,
description="Fired when the user presses a mouse button on an element.",
),
EventTriggers.ON_MOUSE_ENTER: TriggerDefinition(
spec=no_args_event_spec,
description="Fired when the mouse pointer enters the element.",
),
EventTriggers.ON_MOUSE_LEAVE: TriggerDefinition(
spec=no_args_event_spec,
description="Fired when the mouse pointer leaves the element.",
),
EventTriggers.ON_MOUSE_MOVE: TriggerDefinition(
spec=no_args_event_spec,
description="Fired when the mouse pointer moves over the element.",
),
EventTriggers.ON_MOUSE_OUT: TriggerDefinition(
spec=no_args_event_spec,
description="Fired when the mouse pointer moves out of the element.",
),
EventTriggers.ON_MOUSE_OVER: TriggerDefinition(
spec=no_args_event_spec,
description="Fired when the mouse pointer moves onto the element.",
),
EventTriggers.ON_MOUSE_UP: TriggerDefinition(
spec=no_args_event_spec,
description="Fired when the user releases a mouse button on an element.",
),
EventTriggers.ON_SCROLL: TriggerDefinition(
spec=no_args_event_spec,
description="Fired when the user scrolls the element.",
),
EventTriggers.ON_SCROLL_END: TriggerDefinition(
spec=no_args_event_spec,
description="Fired when scrolling ends on the element.",
),
EventTriggers.ON_MOUNT: TriggerDefinition(
spec=no_args_event_spec,
description="Fired when the component is mounted to the page.",
),
EventTriggers.ON_UNMOUNT: TriggerDefinition(
spec=no_args_event_spec,
description="Fired when the component is removed from the page. Only called during navigation, not on page refresh.",
),
}
DEFAULT_TRIGGERS = {
name: trigger.spec for name, trigger in DEFAULT_TRIGGERS_AND_DESC.items()
}
T = TypeVar("T", bound="Component")
class Component(BaseComponent, ABC):
"""A component with style, event trigger and other props."""
style: Style = field(
doc="The style of the component.",
default_factory=Style,
is_javascript_property=False,
)
event_triggers: dict[str, EventChain | Var] = field(
doc="A mapping from event triggers to event chains.",
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)
key: Any = field(
doc="A unique key for the component.",
default=None,
is_javascript_property=False,
)
id: Any = field(
doc="The id for the component.", default=None, is_javascript_property=False
)
ref: Var | None = field(
doc="The Var to pass as the ref to the component.",
default=None,
is_javascript_property=False,
)
class_name: Any = field(
doc="The class name for the component.",
default=None,
is_javascript_property=False,
)
special_props: list[Var] = field(
doc="Special component props.",
default_factory=list,
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_attrs: dict[str, Var | Any] = field(
doc="Attributes passed directly to the component.",
default_factory=dict,
is_javascript_property=False,
)
_memoization_mode: MemoizationMode = field(
doc="When to memoize this component and its children.",
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.
"""
console.error(
"Instantiating components directly is not supported."
f" Use `{self.__class__.__name__}.create` method instead."
)
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()
# Lazily allocate the event_triggers dict only when a trigger is found.
# Most components have no events; allocating up-front is pure waste.
existing_triggers = kwargs.get("event_triggers")
event_triggers: dict[str, Any] | None = (
dict(existing_triggers) if existing_triggers is not None else None
)
event_keys: list[str] = []
# Iterate through the kwargs and set the props.
for key, value in kwargs.items():
if key in component_specific_triggers:
if event_triggers is None:
event_triggers = {}
event_triggers[key] = EventChain.create(
value=value,
args_spec=component_specific_triggers[key],
key=key,
)
event_keys.append(key)
continue
if key in props:
field_def = fields.get(key)
if field_def is None or field_def.type_origin is not Var:
continue
try:
kwargs[key] = LiteralVar.create(value)
passed_type = kwargs[key]._var_type
expected_type = typing.get_args(
types.get_field_type(type(self), key)
)[0]
except TypeError:
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
)
continue
if key.startswith("on_"):
valid_triggers = sorted(component_specific_triggers.keys())