|
| 1 | +"""Custom toggle component.""" |
| 2 | + |
| 3 | +from reflex.components.component import Component |
| 4 | +from reflex.event import EventHandler, passthrough_event_spec |
| 5 | +from reflex.utils.imports import ImportVar |
| 6 | +from reflex.vars import Var |
| 7 | + |
| 8 | +from reflex_ui.components.base_ui import PACKAGE_NAME, BaseUIComponent |
| 9 | + |
| 10 | + |
| 11 | +class ClassNames: |
| 12 | + """Class names for toggle components.""" |
| 13 | + |
| 14 | + ROOT = "flex size-8 items-center justify-center rounded-sm text-secondary-11 select-none hover:bg-secondary-3 focus-visible:bg-none active:bg-secondary-4 data-[pressed]:text-secondary-12 data-[pressed]:bg-secondary-4 transition-colors" |
| 15 | + |
| 16 | + |
| 17 | +class ToggleBaseComponent(BaseUIComponent): |
| 18 | + """Base component for toggle components.""" |
| 19 | + |
| 20 | + library = f"{PACKAGE_NAME}/toggle" |
| 21 | + |
| 22 | + @property |
| 23 | + def import_var(self): |
| 24 | + """Return the import variable for the toggle component.""" |
| 25 | + return ImportVar(tag="Toggle", package_path="", install=False) |
| 26 | + |
| 27 | + |
| 28 | +class Toggle(ToggleBaseComponent): |
| 29 | + """A two-state button that can be on or off. Renders a <button> element.""" |
| 30 | + |
| 31 | + tag = "Toggle" |
| 32 | + |
| 33 | + # A unique string that identifies the toggle when used inside a toggle group. |
| 34 | + value: Var[str] |
| 35 | + |
| 36 | + # Whether the toggle button is currently pressed. This is the uncontrolled counterpart of pressed. Defaults to False. |
| 37 | + default_pressed: Var[bool] |
| 38 | + |
| 39 | + # Whether the toggle button is currently pressed. This is the controlled counterpart of default_pressed. |
| 40 | + pressed: Var[bool] |
| 41 | + |
| 42 | + # Callback fired when the pressed state is changed. |
| 43 | + on_pressed_change: EventHandler[passthrough_event_spec(bool, dict)] |
| 44 | + |
| 45 | + # Whether the component renders a native <button> element when replacing it via the render prop. Set to false if the rendered element is not a button (e.g. <div>). Defaults to True. |
| 46 | + native_button: Var[bool] |
| 47 | + |
| 48 | + # Whether the component should ignore user interaction. Defaults to False. |
| 49 | + disabled: Var[bool] |
| 50 | + |
| 51 | + # The render prop |
| 52 | + render_: Var[Component] |
| 53 | + |
| 54 | + @classmethod |
| 55 | + def create(cls, *children, **props) -> Component: |
| 56 | + """Create the toggle component.""" |
| 57 | + props["data-slot"] = "toggle" |
| 58 | + cls.set_class_name(ClassNames.ROOT, props) |
| 59 | + return super().create(*children, **props) |
| 60 | + |
| 61 | + |
| 62 | +toggle = Toggle.create |
0 commit comments