accordion.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. """Radix accordion components."""
  2. from __future__ import annotations
  3. from typing import Any, Dict, List, Literal, Optional, Union
  4. from reflex.components.component import Component, ComponentNamespace
  5. from reflex.components.core.match import Match
  6. from reflex.components.lucide.icon import Icon
  7. from reflex.components.radix.primitives.base import RadixPrimitiveComponent
  8. from reflex.components.radix.themes.base import LiteralAccentColor
  9. from reflex.style import (
  10. Style,
  11. convert_dict_to_style_and_format_emotion,
  12. format_as_emotion,
  13. )
  14. from reflex.utils import imports
  15. from reflex.vars import BaseVar, Var, VarData, get_uuid_string_var
  16. LiteralAccordionType = Literal["single", "multiple"]
  17. LiteralAccordionDir = Literal["ltr", "rtl"]
  18. LiteralAccordionOrientation = Literal["vertical", "horizontal"]
  19. LiteralAccordionRootVariant = Literal["classic", "soft", "surface", "outline", "ghost"]
  20. LiteralAccordionRootColorScheme = Literal["primary", "accent"]
  21. DEFAULT_ANIMATION_DURATION = 250
  22. def get_theme_accordion_root(variant: Var[str], color_scheme: Var[str]) -> BaseVar:
  23. """Get the theme for the accordion root component.
  24. Args:
  25. variant: The variant of the accordion.
  26. color_scheme: The color of the accordion.
  27. Returns:
  28. The theme for the accordion root component.
  29. """
  30. return Match.create( # type: ignore
  31. variant,
  32. (
  33. "soft",
  34. convert_dict_to_style_and_format_emotion(
  35. {
  36. "border_radius": "6px",
  37. "background_color": f"var(--{color_scheme}-3)",
  38. "box_shadow": "0 2px 10px var(--black-a1)",
  39. }
  40. ),
  41. ),
  42. (
  43. "outline",
  44. convert_dict_to_style_and_format_emotion(
  45. {
  46. "border_radius": "6px",
  47. "border": f"1px solid var(--{color_scheme}-6)",
  48. "box_shadow": "0 2px 10px var(--black-a1)",
  49. }
  50. ),
  51. ),
  52. (
  53. "surface",
  54. convert_dict_to_style_and_format_emotion(
  55. {
  56. "border_radius": "6px",
  57. "border": f"1px solid var(--{color_scheme}-6)",
  58. "background_color": f"var(--{color_scheme}-3)",
  59. "box_shadow": "0 2px 10px var(--black-a1)",
  60. }
  61. ),
  62. ),
  63. (
  64. "ghost",
  65. convert_dict_to_style_and_format_emotion(
  66. {
  67. "border_radius": "6px",
  68. "background_color": "none",
  69. "box_shadow": "None",
  70. }
  71. ),
  72. ),
  73. convert_dict_to_style_and_format_emotion(
  74. {
  75. "border_radius": "6px",
  76. "background_color": f"var(--{color_scheme}-9)",
  77. "box_shadow": "0 2px 10px var(--black-a4)",
  78. }
  79. ),
  80. # defaults to classic
  81. )
  82. def get_theme_accordion_item():
  83. """Get the theme for the accordion item component.
  84. Returns:
  85. The theme for the accordion item component.
  86. """
  87. return convert_dict_to_style_and_format_emotion(
  88. {
  89. "overflow": "hidden",
  90. "width": "100%",
  91. "margin_top": "1px",
  92. "&:first-child": {
  93. "margin_top": 0,
  94. "border_top_left_radius": "4px",
  95. "border_top_right_radius": "4px",
  96. },
  97. "&:last-child": {
  98. "border_bottom_left_radius": "4px",
  99. "border_bottom_right_radius": "4px",
  100. },
  101. "&:focus-within": {
  102. "position": "relative",
  103. "z_index": 1,
  104. },
  105. }
  106. )
  107. def get_theme_accordion_header() -> dict[str, str]:
  108. """Get the theme for the accordion header component.
  109. Returns:
  110. The theme for the accordion header component.
  111. """
  112. return {
  113. "display": "flex",
  114. }
  115. def get_theme_accordion_trigger(variant: str | Var, color_scheme: str | Var) -> BaseVar:
  116. """Get the theme for the accordion trigger component.
  117. Args:
  118. variant: The variant of the accordion.
  119. color_scheme: The color of the accordion.
  120. Returns:
  121. The theme for the accordion trigger component.
  122. """
  123. return Match.create( # type: ignore
  124. variant,
  125. (
  126. "soft",
  127. convert_dict_to_style_and_format_emotion(
  128. {
  129. "color": f"var(--{color_scheme}-11)",
  130. "&:hover": {
  131. "background_color": f"var(--{color_scheme}-4)",
  132. },
  133. "& > .AccordionChevron": {
  134. "color": f"var(--{color_scheme}-11)",
  135. "transition": f"transform {DEFAULT_ANIMATION_DURATION}ms cubic-bezier(0.87, 0, 0.13, 1)",
  136. },
  137. "&[data-state='open'] > .AccordionChevron": {
  138. "transform": "rotate(180deg)",
  139. },
  140. "font_family": "inherit",
  141. "width": "100%",
  142. "padding": "0 20px",
  143. "height": "45px",
  144. "flex": 1,
  145. "display": "flex",
  146. "align_items": "center",
  147. "justify_content": "space-between",
  148. "font_size": "15px",
  149. "line_height": 1,
  150. }
  151. ),
  152. ),
  153. (
  154. "outline",
  155. "surface",
  156. "ghost",
  157. convert_dict_to_style_and_format_emotion(
  158. {
  159. "color": f"var(--{color_scheme}-11)",
  160. "&:hover": {
  161. "background_color": f"var(--{color_scheme}-4)",
  162. },
  163. "& > .AccordionChevron": {
  164. "color": f"var(--{color_scheme}-11)",
  165. "transition": f"transform {DEFAULT_ANIMATION_DURATION}ms cubic-bezier(0.87, 0, 0.13, 1)",
  166. },
  167. "&[data-state='open'] > .AccordionChevron": {
  168. "transform": "rotate(180deg)",
  169. },
  170. "font_family": "inherit",
  171. "width": "100%",
  172. "padding": "0 20px",
  173. "height": "45px",
  174. "flex": 1,
  175. "display": "flex",
  176. "align_items": "center",
  177. "justify_content": "space-between",
  178. "font_size": "15px",
  179. "line_height": 1,
  180. }
  181. ),
  182. ),
  183. # defaults to classic
  184. convert_dict_to_style_and_format_emotion(
  185. {
  186. "color": f"var(--{color_scheme}-9-contrast)",
  187. "box_shadow": f"var(--{color_scheme}-11)",
  188. "&:hover": {
  189. "background_color": f"var(--{color_scheme}-10)",
  190. },
  191. "& > .AccordionChevron": {
  192. "color": f"var(--{color_scheme}-9-contrast)",
  193. "transition": f"transform {DEFAULT_ANIMATION_DURATION}ms cubic-bezier(0.87, 0, 0.13, 1)",
  194. },
  195. "&[data-state='open'] > .AccordionChevron": {
  196. "transform": "rotate(180deg)",
  197. },
  198. "font_family": "inherit",
  199. "width": "100%",
  200. "padding": "0 20px",
  201. "height": "45px",
  202. "flex": 1,
  203. "display": "flex",
  204. "align_items": "center",
  205. "justify_content": "space-between",
  206. "font_size": "15px",
  207. "line_height": 1,
  208. }
  209. ),
  210. )
  211. def get_theme_accordion_content(variant: str | Var, color_scheme: str | Var) -> BaseVar:
  212. """Get the theme for the accordion content component.
  213. Args:
  214. variant: The variant of the accordion.
  215. color_scheme: The color of the accordion.
  216. Returns:
  217. The theme for the accordion content component.
  218. """
  219. return Match.create( # type: ignore
  220. variant,
  221. (
  222. "outline",
  223. "ghost",
  224. convert_dict_to_style_and_format_emotion(
  225. {
  226. "overflow": "hidden",
  227. "font_size": "10px",
  228. "color": f"var(--{color_scheme}-11)",
  229. "padding": "15px 20px",
  230. "&[data-state='open']": {
  231. "animation": Var.create(
  232. f"${{slideDown}} {DEFAULT_ANIMATION_DURATION}ms cubic-bezier(0.87, 0, 0.13, 1)",
  233. _var_is_string=True,
  234. ),
  235. },
  236. "&[data-state='closed']": {
  237. "animation": Var.create(
  238. f"${{slideUp}} {DEFAULT_ANIMATION_DURATION}ms cubic-bezier(0.87, 0, 0.13, 1)",
  239. _var_is_string=True,
  240. ),
  241. },
  242. }
  243. ),
  244. ),
  245. convert_dict_to_style_and_format_emotion(
  246. {
  247. "overflow": "hidden",
  248. "font_size": "10px",
  249. "color": Match.create(
  250. variant,
  251. ("classic", f"var(--{color_scheme}-9-contrast)"),
  252. f"var(--{color_scheme}-11)",
  253. ),
  254. "background_color": Match.create(
  255. variant,
  256. ("classic", f"var(--{color_scheme}-9)"),
  257. f"var(--{color_scheme}-3)",
  258. ),
  259. "padding": "15px 20px",
  260. "&[data-state='open']": {
  261. "animation": Var.create(
  262. f"${{slideDown}} {DEFAULT_ANIMATION_DURATION}ms cubic-bezier(0.87, 0, 0.13, 1)",
  263. _var_is_string=True,
  264. ),
  265. },
  266. "&[data-state='closed']": {
  267. "animation": Var.create(
  268. f"${{slideUp}} {DEFAULT_ANIMATION_DURATION}ms cubic-bezier(0.87, 0, 0.13, 1)",
  269. _var_is_string=True,
  270. ),
  271. },
  272. }
  273. ),
  274. )
  275. class AccordionComponent(RadixPrimitiveComponent):
  276. """Base class for all @radix-ui/accordion components."""
  277. library = "@radix-ui/react-accordion@^1.1.2"
  278. class AccordionRoot(AccordionComponent):
  279. """An accordion component."""
  280. tag = "Root"
  281. alias = "RadixAccordionRoot"
  282. # The type of accordion (single or multiple).
  283. type: Var[LiteralAccordionType]
  284. # The value of the item to expand.
  285. value: Var[Optional[Union[str, List[str]]]]
  286. # The default value of the item to expand.
  287. default_value: Var[Optional[Union[str, List[str]]]]
  288. # Whether or not the accordion is collapsible.
  289. collapsible: Var[bool]
  290. # Whether or not the accordion is disabled.
  291. disabled: Var[bool]
  292. # The reading direction of the accordion when applicable.
  293. dir: Var[LiteralAccordionDir]
  294. # The orientation of the accordion.
  295. orientation: Var[LiteralAccordionOrientation]
  296. # The variant of the accordion.
  297. variant: Var[LiteralAccordionRootVariant] = "classic" # type: ignore
  298. # The color scheme of the accordion.
  299. color_scheme: Var[LiteralAccentColor] # type: ignore
  300. # dynamic themes of the accordion generated at compile time.
  301. _dynamic_themes: Var[dict] = Var.create({}) # type: ignore
  302. # The var_data associated with the component.
  303. _var_data: VarData = VarData() # type: ignore
  304. _valid_children: List[str] = ["AccordionItem"]
  305. @classmethod
  306. def create(cls, *children, **props) -> Component:
  307. """Create the Accordion root component.
  308. Args:
  309. *children: The children of the component.
  310. **props: The properties of the component.
  311. Returns:
  312. The Accordion root Component.
  313. """
  314. comp = super().create(*children, **props)
  315. if comp.color_scheme is not None and not comp.color_scheme._var_state: # type: ignore
  316. # mark the vars of color string literals as strings so they can be formatted properly when performing a var operation.
  317. comp.color_scheme._var_is_string = True # type: ignore
  318. if comp.variant is not None and not comp.variant._var_state: # type: ignore
  319. # mark the vars of variant string literals as strings so they are formatted properly in the match condition.
  320. comp.variant._var_is_string = True # type: ignore
  321. return comp
  322. def _get_style(self) -> dict:
  323. """Get the style for the component.
  324. Returns:
  325. The dictionary of the component style as value and the style notation as key.
  326. """
  327. return {"css": self._dynamic_themes._merge(format_as_emotion(self.style))} # type: ignore
  328. def _apply_theme(self, theme: Component):
  329. global_color_scheme = getattr(theme, "accent_color", None)
  330. if global_color_scheme is None and self.color_scheme is None:
  331. raise ValueError(
  332. "`color_scheme` cannot be None. Either set the `color_scheme` prop on the accordion "
  333. "component or set the `accent_color` prop in your global theme."
  334. )
  335. # prepare the color_scheme var to be used in an f-string(strip off the wrapping curly brace)
  336. color_scheme = Var.create(
  337. self.color_scheme if self.color_scheme is not None else global_color_scheme
  338. )._replace( # type: ignore
  339. _var_is_string=False
  340. )
  341. accordion_theme_root = get_theme_accordion_root(
  342. variant=self.variant, color_scheme=color_scheme
  343. )
  344. accordion_theme_content = get_theme_accordion_content(
  345. variant=self.variant, color_scheme=color_scheme
  346. )
  347. accordion_theme_trigger = get_theme_accordion_trigger(
  348. variant=self.variant, color_scheme=color_scheme
  349. )
  350. # extract var_data from dynamic themes.
  351. self._var_data = (
  352. self._var_data.merge( # type: ignore
  353. accordion_theme_trigger._var_data,
  354. accordion_theme_content._var_data,
  355. accordion_theme_root._var_data,
  356. )
  357. or self._var_data
  358. )
  359. self._dynamic_themes = Var.create( # type: ignore
  360. convert_dict_to_style_and_format_emotion(
  361. {
  362. "& .AccordionItem": get_theme_accordion_item(),
  363. "& .AccordionHeader": get_theme_accordion_header(),
  364. "& .AccordionTrigger": accordion_theme_trigger,
  365. "& .AccordionContent": accordion_theme_content,
  366. }
  367. )
  368. )._merge( # type: ignore
  369. accordion_theme_root
  370. )
  371. def _get_imports_list(self) -> list[imports.ImportVar]:
  372. return [
  373. *super()._get_imports_list(),
  374. *(self._var_data.imports if self._var_data else {}),
  375. imports.ImportVar(package="@emotion/react", tag="keyframes"),
  376. ]
  377. def get_event_triggers(self) -> Dict[str, Any]:
  378. """Get the events triggers signatures for the component.
  379. Returns:
  380. The signatures of the event triggers.
  381. """
  382. return {
  383. **super().get_event_triggers(),
  384. "on_value_change": lambda e0: [e0],
  385. }
  386. def _get_custom_code(self) -> str:
  387. return """
  388. const slideDown = keyframes`
  389. from {
  390. height: 0;
  391. }
  392. to {
  393. height: var(--radix-accordion-content-height);
  394. }
  395. `
  396. const slideUp = keyframes`
  397. from {
  398. height: var(--radix-accordion-content-height);
  399. }
  400. to {
  401. height: 0;
  402. }
  403. `
  404. """
  405. def _exclude_props(self) -> list[str]:
  406. return ["color_scheme", "variant"]
  407. class AccordionItem(AccordionComponent):
  408. """An accordion component."""
  409. tag = "Item"
  410. alias = "RadixAccordionItem"
  411. # A unique identifier for the item.
  412. value: Var[str]
  413. # When true, prevents the user from interacting with the item.
  414. disabled: Var[bool]
  415. _valid_children: List[str] = [
  416. "AccordionHeader",
  417. "AccordionTrigger",
  418. "AccordionContent",
  419. ]
  420. _valid_parents: List[str] = ["AccordionRoot"]
  421. def _apply_theme(self, theme: Component):
  422. self.style = Style(
  423. {
  424. **self.style,
  425. }
  426. )
  427. @classmethod
  428. def create(
  429. cls,
  430. *children,
  431. header: Optional[Component | Var] = None,
  432. content: Optional[Component | Var] = None,
  433. **props,
  434. ) -> Component:
  435. """Create an accordion item.
  436. Args:
  437. header: The header of the accordion item.
  438. content: The content of the accordion item.
  439. *children: The list of children to use if header and content are not provided.
  440. **props: Additional properties to apply to the accordion item.
  441. Returns:
  442. The accordion item.
  443. """
  444. # The item requires a value to toggle (use a random unique name if not provided).
  445. value = props.pop("value", get_uuid_string_var())
  446. if "AccordionItem" not in (
  447. cls_name := props.pop("class_name", "AccordionItem")
  448. ):
  449. cls_name = f"{cls_name} AccordionItem"
  450. if (header is not None) and (content is not None):
  451. children = [
  452. AccordionHeader.create(
  453. AccordionTrigger.create(
  454. header,
  455. AccordionIcon.create(),
  456. ),
  457. ),
  458. AccordionContent.create(content),
  459. ]
  460. return super().create(*children, value=value, **props, class_name=cls_name)
  461. class AccordionHeader(AccordionComponent):
  462. """An accordion component."""
  463. tag = "Header"
  464. alias = "RadixAccordionHeader"
  465. @classmethod
  466. def create(cls, *children, **props) -> Component:
  467. """Create the Accordion header component.
  468. Args:
  469. *children: The children of the component.
  470. **props: The properties of the component.
  471. Returns:
  472. The Accordion header Component.
  473. """
  474. if "AccordionHeader" not in (
  475. cls_name := props.pop("class_name", "AccordionHeader")
  476. ):
  477. cls_name = f"{cls_name} AccordionHeader"
  478. return super().create(*children, class_name=cls_name, **props)
  479. def _apply_theme(self, theme: Component):
  480. self.style = Style({**self.style})
  481. class AccordionTrigger(AccordionComponent):
  482. """An accordion component."""
  483. tag = "Trigger"
  484. alias = "RadixAccordionTrigger"
  485. @classmethod
  486. def create(cls, *children, **props) -> Component:
  487. """Create the Accordion trigger component.
  488. Args:
  489. *children: The children of the component.
  490. **props: The properties of the component.
  491. Returns:
  492. The Accordion trigger Component.
  493. """
  494. if "AccordionTrigger" not in (
  495. cls_name := props.pop("class_name", "AccordionTrigger")
  496. ):
  497. cls_name = f"{cls_name} AccordionTrigger"
  498. return super().create(*children, class_name=cls_name, **props)
  499. def _apply_theme(self, theme: Component):
  500. self.style = Style({**self.style})
  501. class AccordionIcon(Icon):
  502. """An accordion icon component."""
  503. @classmethod
  504. def create(cls, *children, **props) -> Component:
  505. """Create the Accordion icon component.
  506. Args:
  507. *children: The children of the component.
  508. **props: The properties of the component.
  509. Returns:
  510. The Accordion icon Component.
  511. """
  512. if "AccordionChevron" not in (
  513. cls_name := props.pop("class_name", "AccordionChevron")
  514. ):
  515. cls_name = f"{cls_name} AccordionChevron"
  516. return super().create(tag="chevron_down", class_name=cls_name, **props)
  517. class AccordionContent(AccordionComponent):
  518. """An accordion component."""
  519. tag = "Content"
  520. alias = "RadixAccordionContent"
  521. @classmethod
  522. def create(cls, *children, **props) -> Component:
  523. """Create the Accordion content component.
  524. Args:
  525. *children: The children of the component.
  526. **props: The properties of the component.
  527. Returns:
  528. The Accordion content Component.
  529. """
  530. if "AccordionContent" not in (
  531. cls_name := props.pop("class_name", "AccordionContent")
  532. ):
  533. cls_name = f"{cls_name} AccordionContent"
  534. return super().create(*children, class_name=cls_name, **props)
  535. def _apply_theme(self, theme: Component):
  536. self.style = Style({**self.style})
  537. class Accordion(ComponentNamespace):
  538. """Accordion component."""
  539. content = staticmethod(AccordionContent.create)
  540. header = staticmethod(AccordionHeader.create)
  541. item = staticmethod(AccordionItem.create)
  542. icon = staticmethod(AccordionIcon.create)
  543. root = staticmethod(AccordionRoot.create)
  544. trigger = staticmethod(AccordionTrigger.create)
  545. accordion = Accordion()