multiselect.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. """Provides a feature-rich Select and some (not all) related components."""
  2. from __future__ import annotations
  3. from typing import Any, Dict, List, Optional, Set, Union
  4. from reflex.base import Base
  5. from reflex.components.component import Component
  6. from reflex.constants import EventTriggers
  7. from reflex.vars import Var
  8. class Option(Base):
  9. """An option component for the chakra-react-select Select."""
  10. # What is displayed to the user
  11. label: str
  12. # The value of the option, must be serializable
  13. value: Any
  14. # the variant of the option tag
  15. variant: Optional[str] = None
  16. # [not working yet]
  17. # Whether the option is disabled
  18. # is_disabled: Optional[bool] = None
  19. # [not working yet]
  20. # The visual color appearance of the component
  21. # options: "whiteAlpha" | "blackAlpha" | "gray" | "red" |
  22. # "orange" | "yellow" | "green" | "teal" | "blue" | "cyan" |
  23. # "purple" | "pink" | "linkedin" | "facebook" | "messenger" |
  24. # "whatsapp" | "twitter" | "telegram"
  25. # default: "gray"
  26. # color_scheme: Optional[str] = None
  27. # [not working yet]
  28. # The icon of the option tag
  29. # icon: Optional[str] = None
  30. class Select(Component):
  31. """The default chakra-react-select Select component.
  32. Not every available prop is listed here,
  33. for a complete overview check the react-select/chakra-react-select docs.
  34. Props added by chakra-react-select are marked with "[chakra]".
  35. """
  36. library = "chakra-react-select"
  37. tag = "Select"
  38. # Focus the control when it is mounted
  39. auto_focus: Var[bool]
  40. # Remove the currently focused option when the user presses backspace
  41. # when Select isClearable or isMulti
  42. backspace_removes_value: Var[bool]
  43. # Remove focus from the input when the user selects an option
  44. # (handy for dismissing the keyboard on touch devices)
  45. blur_input_on_select: Var[bool]
  46. # When the user reaches the top/bottom of the menu,
  47. # prevent scroll on the scroll-parent
  48. capture_menu_scroll: Var[bool]
  49. # [chakra]
  50. # To use the chakraStyles prop, first,
  51. # check the documentation for the original styles prop from the react-select docs.
  52. # This package offers an identical API for the chakraStyles prop, however,
  53. # the provided and output style objects use Chakra's sx prop
  54. # instead of the default emotion styles the original package offers.
  55. # This allows you to both use the shorthand styling props you'd normally use
  56. # to style Chakra components, as well as tokens from your theme such as named colors.
  57. # All of the style keys offered in the original package can be used in the chakraStyles prop
  58. # except for menuPortal. Along with some other caveats, this is explained below.
  59. # Most of the components rendered by this package use the basic Chakra <Box /> component with a few exceptions.
  60. # Here are the style keys offered and the corresponding Chakra component that is rendered:
  61. # - clearIndicator - Box (uses theme styles for Chakra's CloseButton)
  62. # - container - Box
  63. # - control - Box (uses theme styles for Chakra's Input)
  64. # - dropdownIndicator - Box (uses theme styles for Chrakra's InputRightAddon)
  65. # - downChevron - Icon
  66. # - crossIcon - Icon
  67. # - group - Box
  68. # - groupHeading - Box (uses theme styles for Chakra's Menu group title)
  69. # - indicatorsContainer - Box
  70. # - indicatorSeparator - Divider
  71. # - input - chakra.input (wrapped in a Box)
  72. # - inputContainer - Box
  73. # - loadingIndicator - Spinner
  74. # - loadingMessage - Box
  75. # - menu - Box
  76. # - menuList - Box (uses theme styles for Chakra's Menu)
  77. # - multiValue - chakra.span (uses theme styles for Chakra's Tag)
  78. # - multiValueLabel - chakra.span (uses theme styles for Chakra's TagLabel)
  79. # - multiValueRemove - Box (uses theme styles for Chakra's TagCloseButton)
  80. # - noOptionsMessage - Box
  81. # - option - Box (uses theme styles for Chakra's MenuItem)
  82. # - placeholder - Box
  83. # - singleValue - Box
  84. # - valueContainer - Box
  85. chakra_styles: Var[str]
  86. # Close the select menu when the user selects an option
  87. close_menu_on_select: Var[bool]
  88. # If true, close the select menu when the user scrolls the document/body.
  89. close_menu_on_scroll: Var[bool]
  90. # [chakra]
  91. # The visual color appearance of the component
  92. # options: "whiteAlpha" | "blackAlpha" | "gray" | "red" |
  93. # "orange" | "yellow" | "green" | "teal" | "blue" | "cyan" |
  94. # "purple" | "pink" | "linkedin" | "facebook" | "messenger" |
  95. # "whatsapp" | "twitter" | "telegram"
  96. # default: "gray"
  97. color_scheme: Var[str]
  98. # This complex object includes all the compositional components
  99. # that are used in react-select. If you wish to overwrite a component,
  100. # pass in an object with the appropriate namespace.
  101. # If you only wish to restyle a component,
  102. # we recommend using the styles prop instead.
  103. components: Var[Dict[str, Component]]
  104. # Whether the value of the select, e.g. SingleValue,
  105. # should be displayed in the control.
  106. control_should_render_value: Var[bool]
  107. # Delimiter used to join multiple values into a single HTML Input value
  108. delimiter: Var[str]
  109. # [chakra]
  110. # Colors the component border with the given chakra color string on error state
  111. # default: "red.500"
  112. error_border_color: Var[str]
  113. # Clear all values when the user presses escape AND the menu is closed
  114. escape_clears_value: Var[bool]
  115. # [chakra]
  116. # Colors the component border with the given chakra color string on focus
  117. # default: "blue.500"
  118. focus_border_color: Var[str]
  119. # Sets the form attribute on the input
  120. form: Var[str]
  121. # Hide the selected option from the menu
  122. hide_selected_options: Var[bool]
  123. # The id to set on the SelectContainer component.
  124. # id: Var[str]
  125. # The value of the search input
  126. input_value: Var[str]
  127. # The id of the search input
  128. input_id: Var[str]
  129. # Is the select value clearable
  130. is_clearable: Var[bool]
  131. # Is the select disabled
  132. is_disabled: Var[bool]
  133. # [chakra]
  134. # Style component in the chakra invalid style
  135. # default: False
  136. is_invalid: Var[bool]
  137. # Support multiple selected options
  138. is_multi: Var[bool]
  139. # [chakra]
  140. # Style component as disabled (chakra style)
  141. # default: False
  142. is_read_only: Var[bool]
  143. # Is the select direction right-to-left
  144. is_rtl: Var[bool]
  145. # Whether to enable search functionality
  146. is_searchable: Var[bool]
  147. # Minimum height of the menu before flipping
  148. min_menu_height: Var[int]
  149. # Maximum height of the menu before scrolling
  150. max_menu_height: Var[int]
  151. # Default placement of the menu in relation to the control.
  152. # 'auto' will flip when there isn't enough space below the control.
  153. # options: "bottom" | "auto" | "top"
  154. menu_placement: Var[str]
  155. # The CSS position value of the menu,
  156. # when "fixed" extra layout management is required
  157. # options: "absolute" | "fixed"
  158. menu_position: Var[str]
  159. # Whether to block scroll events when the menu is open
  160. menu_should_block_scroll: Var[bool]
  161. # Whether the menu should be scrolled into view when it opens
  162. menu_should_scroll_into_view: Var[bool]
  163. # Name of the HTML Input (optional - without this, no input will be rendered)
  164. name: Var[str]
  165. # Allows control of whether the menu is opened when the Select is focused
  166. open_menu_on_focus: Var[bool]
  167. # Allows control of whether the menu is opened when the Select is clicked
  168. open_menu_on_click: Var[bool]
  169. # Array of options that populate the select menu
  170. options: Var[List[Dict]]
  171. # Number of options to jump in menu when page{up|down} keys are used
  172. page_size: Var[int]
  173. # Placeholder for the select value
  174. placeholder: Var[Optional[str]]
  175. # Marks the value-holding input as required for form validation
  176. required: Var[bool]
  177. # [chakra]
  178. # If you choose to stick with the default selectedOptionStyle="color",
  179. # you have one additional styling option.
  180. # If you do not like the default of blue for the highlight color,
  181. # you can pass the selectedOptionColorScheme prop to change it.
  182. # This prop will accept any named color from your theme's color palette,
  183. # and it will use the 500 value in light mode or the 300 value in dark mode.
  184. # This prop can only be used for named colors from your theme, not arbitrary hex/rgb colors.
  185. # If you would like to use a specific color for the background that's not a part of your theme,
  186. # use the chakraStyles prop to customize it.
  187. # default: "blue"
  188. selected_option_color_scheme: Var[str]
  189. # [chakra]
  190. # The default option "color" will style a selected option
  191. # similar to how react-select does it,
  192. # by highlighting the selected option in the color blue.
  193. # Alternatively, if you pass "check" for the value,
  194. # the selected option will be styled like the Chakra UI Menu component
  195. # and include a check icon next to the selected option(s).
  196. # If is_multi and selected_option_style="check" are passed,
  197. # space will only be added for the check marks
  198. # if hide_selected_options=False is also passed.
  199. # options: "color" | "check"
  200. # default: "color"
  201. selected_option_style: Var[str]
  202. # [chakra]
  203. # The size of the component.
  204. # options: "sm" | "md" | "lg"
  205. # default: "md"
  206. size: Var[str]
  207. # Sets the tabIndex attribute on the input
  208. tab_index: Var[int]
  209. # Select the currently focused option when the user presses tab
  210. tab_selects_value: Var[bool]
  211. # [chakra]
  212. # Variant of multi-select tags
  213. # options: "subtle" | "solid" | "outline"
  214. # default: "subtle"
  215. tag_variant: Var[str]
  216. # Remove all non-essential styles
  217. unstyled: Var[bool]
  218. # [chakra]
  219. # If this prop is passed,
  220. # the dropdown indicator at the right of the component will be styled
  221. # in the same way the original Chakra Select component is styled,
  222. # instead of being styled as an InputRightAddon.
  223. # The original purpose of styling it as an addon
  224. # was to create a visual separation between the dropdown indicator
  225. # and the button for clearing the selected options.
  226. # However, as this button only appears when isMulti is passed,
  227. # using this style could make more sense for a single select.
  228. # default: False
  229. use_basic_style: Var[bool]
  230. # [chakra]
  231. # The variant of the Select. If no variant is passed,
  232. # it will default to defaultProps.variant from the theme for Chakra's Input component.
  233. # If your component theme for Input is not modified, it will be outline.
  234. # options: "outline" | "filled" | "flushed" | "unstyled"
  235. # default: "outline"
  236. variant: Var[str]
  237. # How the options should be displayed in the menu.
  238. menu_position: Var[str] = "fixed" # type: ignore
  239. def get_event_triggers(self) -> dict[str, Union[Var, Any]]:
  240. """Get the event triggers that pass the component's value to the handler.
  241. Returns:
  242. A dict mapping the event trigger to the var that is passed to the handler.
  243. """
  244. return {
  245. **super().get_event_triggers(),
  246. EventTriggers.ON_CHANGE: (
  247. lambda e0: [
  248. Var.create_safe(f"{e0}.map(e => e.value)", _var_is_local=True)
  249. ]
  250. if self.is_multi
  251. else lambda e0: [e0]
  252. ),
  253. }
  254. @classmethod
  255. def get_initial_props(cls) -> Set[str]:
  256. """Get the initial props to set for the component.
  257. Returns:
  258. The initial props to set.
  259. """
  260. return super().get_initial_props() | {"is_multi"}
  261. @classmethod
  262. def create(
  263. cls, options: List[Union[Option, str, int, float, bool]], **props
  264. ) -> Component:
  265. """Takes a list of options and additional properties, checks if each option is an
  266. instance of Option, and returns a Select component with the given options and
  267. properties. No children allowed.
  268. Args:
  269. options (List[Option | str | int | float | bool]): A list of values.
  270. **props: Additional properties to be passed to the Select component.
  271. Returns:
  272. The `create` method is returning an instance of the `Select` class.
  273. """
  274. converted_options: List[Option] = []
  275. for option in options:
  276. if not isinstance(option, Option):
  277. converted_options.append(Option(label=str(option), value=option))
  278. else:
  279. converted_options.append(option)
  280. props["options"] = [o.dict() for o in converted_options]
  281. return super().create(*[], **props)