123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486 |
- """Radix accordion components."""
- from __future__ import annotations
- from typing import Any, Dict, List, Literal, Optional, Union
- from reflex.components.component import Component, ComponentNamespace
- from reflex.components.core.colors import color
- from reflex.components.lucide.icon import Icon
- from reflex.components.radix.primitives.base import RadixPrimitiveComponent
- from reflex.components.radix.themes.base import LiteralAccentColor
- from reflex.style import Style
- from reflex.utils import imports
- from reflex.vars import Var, get_uuid_string_var
- LiteralAccordionType = Literal["single", "multiple"]
- LiteralAccordionDir = Literal["ltr", "rtl"]
- LiteralAccordionOrientation = Literal["vertical", "horizontal"]
- LiteralAccordionVariant = Literal["classic", "soft", "surface", "outline", "ghost"]
- DEFAULT_ANIMATION_DURATION = 250
- class AccordionComponent(RadixPrimitiveComponent):
- """Base class for all @radix-ui/accordion components."""
- library = "@radix-ui/react-accordion@^1.1.2"
- # The color scheme of the component.
- color_scheme: Var[LiteralAccentColor]
- # The variant of the component.
- variant: Var[LiteralAccordionVariant] = Var.create_safe("classic")
- def add_style(self) -> Style | None:
- """Add style to the component."""
- if self.color_scheme is not None:
- self.custom_attrs["data-accent-color"] = self.color_scheme
- self.custom_attrs["data-variant"] = self.variant
- def _exclude_props(self) -> list[str]:
- return ["color_scheme", "variant"]
- class AccordionRoot(AccordionComponent):
- """An accordion component."""
- tag = "Root"
- alias = "RadixAccordionRoot"
- # The type of accordion (single or multiple).
- type: Var[LiteralAccordionType]
- # The value of the item to expand.
- value: Var[Union[str, List[str]]]
- # The default value of the item to expand.
- default_value: Var[Union[str, List[str]]]
- # Whether or not the accordion is collapsible.
- collapsible: Var[bool]
- # Whether or not the accordion is disabled.
- disabled: Var[bool]
- # The reading direction of the accordion when applicable.
- dir: Var[LiteralAccordionDir]
- # The orientation of the accordion.
- orientation: Var[LiteralAccordionOrientation]
- # The variant of the accordion.
- variant: Var[LiteralAccordionVariant] = Var.create_safe("classic")
- _valid_children: List[str] = ["AccordionItem"]
- @classmethod
- def create(cls, *children, **props) -> Component:
- """Create the Accordion root component.
- Args:
- *children: The children of the component.
- **props: The properties of the component.
- Returns:
- The Accordion root Component.
- """
- for child in children:
- if isinstance(child, AccordionItem):
- child.color_scheme = props.get("color_scheme") # type: ignore
- child.variant = props.get("variant") # type: ignore
- return super().create(*children, **props)
- def get_event_triggers(self) -> Dict[str, Any]:
- """Get the events triggers signatures for the component.
- Returns:
- The signatures of the event triggers.
- """
- return {
- **super().get_event_triggers(),
- "on_value_change": lambda e0: [e0],
- }
- def add_style(self):
- """Add style to the component.
- Returns:
- The style of the component.
- """
- return Style(
- {
- "border_radius": "6px",
- "box_shadow": f"0 2px 10px {color('black', 1, alpha=True)}",
- "&[data-variant='classic']": {
- "background_color": color("accent", 9),
- "box_shadow": f"0 2px 10px {color('black', 4, alpha=True)}",
- },
- "&[data-variant='soft']": {
- "background_color": color("accent", 3),
- },
- "&[data-variant='outline']": {
- "border": f"1px solid {color('accent', 6)}",
- },
- "&[data-variant='surface']": {
- "border": f"1px solid {color('accent', 6)}",
- "background_color": color("accent", 3),
- },
- "&[data-variant='ghost']": {
- "background_color": "none",
- "box_shadow": "None",
- },
- }
- )
- class AccordionItem(AccordionComponent):
- """An accordion component."""
- tag = "Item"
- alias = "RadixAccordionItem"
- # A unique identifier for the item.
- value: Var[str]
- # When true, prevents the user from interacting with the item.
- disabled: Var[bool]
- _valid_children: List[str] = [
- "AccordionHeader",
- "AccordionTrigger",
- "AccordionContent",
- ]
- _valid_parents: List[str] = ["AccordionRoot"]
- @classmethod
- def create(
- cls,
- *children,
- header: Optional[Component | Var] = None,
- content: Optional[Component | Var] = None,
- **props,
- ) -> Component:
- """Create an accordion item.
- Args:
- *children: The list of children to use if header and content are not provided.
- header: The header of the accordion item.
- content: The content of the accordion item.
- **props: Additional properties to apply to the accordion item.
- Returns:
- The accordion item.
- """
- # The item requires a value to toggle (use a random unique name if not provided).
- value = props.pop("value", get_uuid_string_var())
- if "AccordionItem" not in (
- cls_name := props.pop("class_name", "AccordionItem")
- ):
- cls_name = f"{cls_name} AccordionItem"
- if (header is not None) and (content is not None):
- children = [
- AccordionHeader.create(
- AccordionTrigger.create(
- header,
- AccordionIcon.create(
- color_scheme=props.get("color_scheme"),
- variant=props.get("variant"),
- ),
- color_scheme=props.get("color_scheme"),
- variant=props.get("variant"),
- ),
- color_scheme=props.get("color_scheme"),
- variant=props.get("variant"),
- ),
- AccordionContent.create(
- content, color_scheme=props.get("color_scheme")
- ),
- ]
- return super().create(*children, value=value, **props, class_name=cls_name)
- def add_style(self) -> Style | None:
- """Add style to the component.
- Returns:
- The style of the component.
- """
- for child in self.children:
- if isinstance(child, (AccordionHeader, AccordionContent)):
- child.color_scheme = self.color_scheme
- child.variant = self.variant
- return Style(
- {
- "overflow": "hidden",
- "width": "100%",
- "margin_top": "1px",
- "&:first-child": {
- "margin_top": 0,
- "border_top_left_radius": "4px",
- "border_top_right_radius": "4px",
- },
- "&:last-child": {
- "border_bottom_left_radius": "4px",
- "border_bottom_right_radius": "4px",
- },
- "&:focus-within": {
- "position": "relative",
- "z_index": 1,
- },
- }
- )
- class AccordionHeader(AccordionComponent):
- """An accordion component."""
- tag = "Header"
- alias = "RadixAccordionHeader"
- @classmethod
- def create(cls, *children, **props) -> Component:
- """Create the Accordion header component.
- Args:
- *children: The children of the component.
- **props: The properties of the component.
- Returns:
- The Accordion header Component.
- """
- if "AccordionHeader" not in (
- cls_name := props.pop("class_name", "AccordionHeader")
- ):
- cls_name = f"{cls_name} AccordionHeader"
- return super().create(*children, class_name=cls_name, **props)
- def add_style(self) -> Style | None:
- """Add style to the component.
- Returns:
- The style of the component.
- """
- for child in self.children:
- if isinstance(child, AccordionTrigger):
- child.color_scheme = self.color_scheme
- child.variant = self.variant
- return Style({"display": "flex"})
- cubic_bezier = "cubic-bezier(0.87, 0, 0.13, 1)"
- class AccordionTrigger(AccordionComponent):
- """An accordion component."""
- tag = "Trigger"
- alias = "RadixAccordionTrigger"
- @classmethod
- def create(cls, *children, **props) -> Component:
- """Create the Accordion trigger component.
- Args:
- *children: The children of the component.
- **props: The properties of the component.
- Returns:
- The Accordion trigger Component.
- """
- if "AccordionTrigger" not in (
- cls_name := props.pop("class_name", "AccordionTrigger")
- ):
- cls_name = f"{cls_name} AccordionTrigger"
- return super().create(*children, class_name=cls_name, **props)
- def add_style(self) -> Style | None:
- """Add style to the component.
- Returns:
- The style of the component.
- """
- for child in self.children:
- if isinstance(child, AccordionIcon):
- child.color_scheme = self.color_scheme
- child.variant = self.variant
- return Style(
- {
- "color": color("accent", 11),
- "line_height": 1,
- "font_size": "15px",
- "justify_content": "space-between",
- "align_items": "center",
- "flex": 1,
- "display": "flex",
- "padding": "0 20px",
- "height": "45px",
- "font_family": "inherit",
- "width": "100%",
- "&[data-state='open'] > .AccordionChevron": {
- "transform": "rotate(180deg)",
- },
- "&:hover": {
- "background_color": color("accent", 4),
- },
- "& > .AccordionChevron": {
- "transition": f"transform {DEFAULT_ANIMATION_DURATION}ms {cubic_bezier}",
- },
- "&[data-variant='classic']": {
- "color": color("accent", 12),
- "box_shadow": color("accent", 11),
- "&:hover": {
- "background_color": color("accent", 10),
- },
- "& > .AccordionChevron": {
- "color": color("accent", 12),
- "transition": f"transform {DEFAULT_ANIMATION_DURATION}ms {cubic_bezier}",
- },
- },
- }
- )
- class AccordionIcon(Icon):
- """An accordion icon component."""
- @classmethod
- def create(cls, *children, **props) -> Component:
- """Create the Accordion icon component.
- Args:
- *children: The children of the component.
- **props: The properties of the component.
- Returns:
- The Accordion icon Component.
- """
- if "AccordionChevron" not in (
- cls_name := props.pop("class_name", "AccordionChevron")
- ):
- cls_name = f"{cls_name} AccordionChevron"
- return super().create(tag="chevron_down", class_name=cls_name, **props)
- class AccordionContent(AccordionComponent):
- """An accordion component."""
- tag = "Content"
- alias = "RadixAccordionContent"
- def add_imports(self) -> imports.ImportDict:
- """Add imports to the component.
- Returns:
- The imports of the component.
- """
- return {"@emotion/react": [imports.ImportVar(tag="keyframes")]}
- @classmethod
- def create(cls, *children, **props) -> Component:
- """Create the Accordion content component.
- Args:
- *children: The children of the component.
- **props: The properties of the component.
- Returns:
- The Accordion content Component.
- """
- if "AccordionContent" not in (
- cls_name := props.pop("class_name", "AccordionContent")
- ):
- cls_name = f"{cls_name} AccordionContent"
- return super().create(*children, class_name=cls_name, **props)
- def add_custom_code(self) -> list[str]:
- """Add custom code to the component.
- Returns:
- The custom code of the component.
- """
- return [
- """
- const slideDown = keyframes`
- from {
- height: 0;
- }
- to {
- height: var(--radix-accordion-content-height);
- }
- `
- const slideUp = keyframes`
- from {
- height: var(--radix-accordion-content-height);
- }
- to {
- height: 0;
- }
- `
- """
- ]
- def add_style(self) -> Style | None:
- """Add style to the component.
- Returns:
- The style of the component.
- """
- slideDown = Var.create(
- f"${{slideDown}} {DEFAULT_ANIMATION_DURATION}ms {cubic_bezier}",
- _var_is_string=True,
- )
- slideUp = Var.create(
- f"${{slideUp}} {DEFAULT_ANIMATION_DURATION}ms {cubic_bezier}",
- _var_is_string=True,
- )
- return Style(
- {
- "overflow": "hidden",
- "font_size": "10px",
- "color": color("accent", 11),
- "background_color": color("accent", 3),
- "padding": "0 15px",
- "&[data-state='open']": {"animation": slideDown},
- "&[data-state='closed']": {"animation": slideUp},
- "&[data-variant='classic']": {
- "color": color("accent", 12),
- "background_color": color("accent", 9),
- },
- "&[data-variant='outline']": {"background_color": "transparent"},
- "&[data-variant='ghost']": {"background_color": "transparent"},
- }
- )
- class Accordion(ComponentNamespace):
- """Accordion component."""
- content = staticmethod(AccordionContent.create)
- header = staticmethod(AccordionHeader.create)
- item = staticmethod(AccordionItem.create)
- icon = staticmethod(AccordionIcon.create)
- root = staticmethod(AccordionRoot.create)
- trigger = staticmethod(AccordionTrigger.create)
- accordion = Accordion()
|