multiselect.py 12 KB

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