forms.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. """Forms classes."""
  2. from __future__ import annotations
  3. from hashlib import md5
  4. from typing import Any, Dict, Iterator, Set, Tuple, Union
  5. from jinja2 import Environment
  6. from reflex.components.el.element import Element
  7. from reflex.components.tags.tag import Tag
  8. from reflex.constants import Dirs, EventTriggers
  9. from reflex.event import (
  10. EventChain,
  11. EventHandler,
  12. input_event,
  13. key_event,
  14. prevent_default,
  15. )
  16. from reflex.utils.imports import ImportDict
  17. from reflex.vars import VarData
  18. from reflex.vars.base import LiteralVar, Var
  19. from .base import BaseHTML
  20. FORM_DATA = Var(_js_expr="form_data")
  21. HANDLE_SUBMIT_JS_JINJA2 = Environment().from_string(
  22. """
  23. const handleSubmit_{{ handle_submit_unique_name }} = useCallback((ev) => {
  24. const $form = ev.target
  25. ev.preventDefault()
  26. const {{ form_data }} = {...Object.fromEntries(new FormData($form).entries()), ...{{ field_ref_mapping }}};
  27. ({{ on_submit_event_chain }}());
  28. if ({{ reset_on_submit }}) {
  29. $form.reset()
  30. }
  31. })
  32. """
  33. )
  34. class Button(BaseHTML):
  35. """Display the button element."""
  36. tag = "button"
  37. # Automatically focuses the button when the page loads
  38. auto_focus: Var[Union[str, int, bool]]
  39. # Disables the button
  40. disabled: Var[bool]
  41. # Associates the button with a form (by id)
  42. form: Var[Union[str, int, bool]]
  43. # URL to send the form data to (for type="submit" buttons)
  44. form_action: Var[Union[str, int, bool]]
  45. # How the form data should be encoded when submitting to the server (for type="submit" buttons)
  46. form_enc_type: Var[Union[str, int, bool]]
  47. # HTTP method to use for sending form data (for type="submit" buttons)
  48. form_method: Var[Union[str, int, bool]]
  49. # Bypasses form validation when submitting (for type="submit" buttons)
  50. form_no_validate: Var[Union[str, int, bool]]
  51. # Specifies where to display the response after submitting the form (for type="submit" buttons)
  52. form_target: Var[Union[str, int, bool]]
  53. # Name of the button, used when sending form data
  54. name: Var[Union[str, int, bool]]
  55. # Type of the button (submit, reset, or button)
  56. type: Var[Union[str, int, bool]]
  57. # Value of the button, used when sending form data
  58. value: Var[Union[str, int, bool]]
  59. class Datalist(BaseHTML):
  60. """Display the datalist element."""
  61. tag = "datalist"
  62. class Fieldset(Element):
  63. """Display the fieldset element."""
  64. tag = "fieldset"
  65. # Disables all the form control descendants of the fieldset
  66. disabled: Var[Union[str, int, bool]]
  67. # Associates the fieldset with a form (by id)
  68. form: Var[Union[str, int, bool]]
  69. # Name of the fieldset, used for scripting
  70. name: Var[Union[str, int, bool]]
  71. def on_submit_event_spec() -> Tuple[Var[Dict[str, Any]]]:
  72. """Event handler spec for the on_submit event.
  73. Returns:
  74. The event handler spec.
  75. """
  76. return (FORM_DATA,)
  77. def on_submit_string_event_spec() -> Tuple[Var[Dict[str, str]]]:
  78. """Event handler spec for the on_submit event.
  79. Returns:
  80. The event handler spec.
  81. """
  82. return (FORM_DATA,)
  83. class Form(BaseHTML):
  84. """Display the form element."""
  85. tag = "form"
  86. # MIME types the server accepts for file upload
  87. accept: Var[Union[str, int, bool]]
  88. # Character encodings to be used for form submission
  89. accept_charset: Var[Union[str, int, bool]]
  90. # URL where the form's data should be submitted
  91. action: Var[Union[str, int, bool]]
  92. # Whether the form should have autocomplete enabled
  93. auto_complete: Var[Union[str, int, bool]]
  94. # Encoding type for the form data when submitted
  95. enc_type: Var[Union[str, int, bool]]
  96. # HTTP method to use for form submission
  97. method: Var[Union[str, int, bool]]
  98. # Name of the form
  99. name: Var[Union[str, int, bool]]
  100. # Indicates that the form should not be validated on submit
  101. no_validate: Var[Union[str, int, bool]]
  102. # Where to display the response after submitting the form
  103. target: Var[Union[str, int, bool]]
  104. # If true, the form will be cleared after submit.
  105. reset_on_submit: Var[bool] = False # type: ignore
  106. # The name used to make this form's submit handler function unique.
  107. handle_submit_unique_name: Var[str]
  108. # Fired when the form is submitted
  109. on_submit: EventHandler[on_submit_event_spec, on_submit_string_event_spec]
  110. @classmethod
  111. def create(cls, *children, **props):
  112. """Create a form component.
  113. Args:
  114. *children: The children of the form.
  115. **props: The properties of the form.
  116. Returns:
  117. The form component.
  118. """
  119. if "on_submit" not in props:
  120. props["on_submit"] = prevent_default
  121. if "handle_submit_unique_name" in props:
  122. return super().create(*children, **props)
  123. # Render the form hooks and use the hash of the resulting code to create a unique name.
  124. props["handle_submit_unique_name"] = ""
  125. form = super().create(*children, **props)
  126. form.handle_submit_unique_name = md5(
  127. str({**form._get_all_hooks_internal(), **form._get_all_hooks()}).encode(
  128. "utf-8"
  129. )
  130. ).hexdigest()
  131. return form
  132. def add_imports(self) -> ImportDict:
  133. """Add imports needed by the form component.
  134. Returns:
  135. The imports for the form component.
  136. """
  137. return {
  138. "react": "useCallback",
  139. f"$/{Dirs.STATE_PATH}": ["getRefValue", "getRefValues"],
  140. }
  141. def add_hooks(self) -> list[str]:
  142. """Add hooks for the form.
  143. Returns:
  144. The hooks for the form.
  145. """
  146. if EventTriggers.ON_SUBMIT not in self.event_triggers:
  147. return []
  148. return [
  149. HANDLE_SUBMIT_JS_JINJA2.render(
  150. handle_submit_unique_name=self.handle_submit_unique_name,
  151. form_data=FORM_DATA,
  152. field_ref_mapping=str(LiteralVar.create(self._get_form_refs())),
  153. on_submit_event_chain=str(
  154. LiteralVar.create(self.event_triggers[EventTriggers.ON_SUBMIT])
  155. ),
  156. reset_on_submit=self.reset_on_submit,
  157. )
  158. ]
  159. def _render(self) -> Tag:
  160. render_tag = super()._render()
  161. if EventTriggers.ON_SUBMIT in self.event_triggers:
  162. render_tag.add_props(
  163. **{
  164. EventTriggers.ON_SUBMIT: Var(
  165. _js_expr=f"handleSubmit_{self.handle_submit_unique_name}",
  166. _var_type=EventChain,
  167. )
  168. }
  169. )
  170. return render_tag
  171. def _get_form_refs(self) -> Dict[str, Any]:
  172. # Send all the input refs to the handler.
  173. form_refs = {}
  174. for ref in self._get_all_refs():
  175. # when ref start with refs_ it's an array of refs, so we need different method
  176. # to collect data
  177. if ref.startswith("refs_"):
  178. ref_var = Var(_js_expr=ref[:-3])._as_ref()
  179. form_refs[ref[len("refs_") : -3]] = Var(
  180. _js_expr=f"getRefValues({ref_var!s})",
  181. _var_data=VarData.merge(ref_var._get_all_var_data()),
  182. )
  183. else:
  184. ref_var = Var(_js_expr=ref)._as_ref()
  185. form_refs[ref[4:]] = Var(
  186. _js_expr=f"getRefValue({ref_var!s})",
  187. _var_data=VarData.merge(ref_var._get_all_var_data()),
  188. )
  189. return form_refs
  190. def _get_vars(self, include_children: bool = True) -> Iterator[Var]:
  191. yield from super()._get_vars(include_children=include_children)
  192. yield from self._get_form_refs().values()
  193. def _exclude_props(self) -> list[str]:
  194. return [
  195. *super()._exclude_props(),
  196. "reset_on_submit",
  197. "handle_submit_unique_name",
  198. ]
  199. class Input(BaseHTML):
  200. """Display the input element."""
  201. tag = "input"
  202. # Accepted types of files when the input is file type
  203. accept: Var[Union[str, int, bool]]
  204. # Alternate text for input type="image"
  205. alt: Var[Union[str, int, bool]]
  206. # Whether the input should have autocomplete enabled
  207. auto_complete: Var[Union[str, int, bool]]
  208. # Automatically focuses the input when the page loads
  209. auto_focus: Var[Union[str, int, bool]]
  210. # Captures media from the user (camera or microphone)
  211. capture: Var[Union[str, int, bool]]
  212. # Indicates whether the input is checked (for checkboxes and radio buttons)
  213. checked: Var[Union[str, int, bool]]
  214. # The initial value (for checkboxes and radio buttons)
  215. default_checked: Var[bool]
  216. # The initial value for a text field
  217. default_value: Var[str]
  218. # Name part of the input to submit in 'dir' and 'name' pair when form is submitted
  219. dirname: Var[Union[str, int, bool]]
  220. # Disables the input
  221. disabled: Var[Union[str, int, bool]]
  222. # Associates the input with a form (by id)
  223. form: Var[Union[str, int, bool]]
  224. # URL to send the form data to (for type="submit" buttons)
  225. form_action: Var[Union[str, int, bool]]
  226. # How the form data should be encoded when submitting to the server (for type="submit" buttons)
  227. form_enc_type: Var[Union[str, int, bool]]
  228. # HTTP method to use for sending form data (for type="submit" buttons)
  229. form_method: Var[Union[str, int, bool]]
  230. # Bypasses form validation when submitting (for type="submit" buttons)
  231. form_no_validate: Var[Union[str, int, bool]]
  232. # Specifies where to display the response after submitting the form (for type="submit" buttons)
  233. form_target: Var[Union[str, int, bool]]
  234. # References a datalist for suggested options
  235. list: Var[Union[str, int, bool]]
  236. # Specifies the maximum value for the input
  237. max: Var[Union[str, int, bool]]
  238. # Specifies the maximum number of characters allowed in the input
  239. max_length: Var[Union[str, int, bool]]
  240. # Specifies the minimum number of characters required in the input
  241. min_length: Var[Union[str, int, bool]]
  242. # Specifies the minimum value for the input
  243. min: Var[Union[str, int, bool]]
  244. # Indicates whether multiple values can be entered in an input of the type email or file
  245. multiple: Var[Union[str, int, bool]]
  246. # Name of the input, used when sending form data
  247. name: Var[Union[str, int, bool]]
  248. # Regex pattern the input's value must match to be valid
  249. pattern: Var[Union[str, int, bool]]
  250. # Placeholder text in the input
  251. placeholder: Var[Union[str, int, bool]]
  252. # Indicates whether the input is read-only
  253. read_only: Var[Union[str, int, bool]]
  254. # Indicates that the input is required
  255. required: Var[Union[str, int, bool]]
  256. # Specifies the visible width of a text control
  257. size: Var[Union[str, int, bool]]
  258. # URL for image inputs
  259. src: Var[Union[str, int, bool]]
  260. # Specifies the legal number intervals for an input
  261. step: Var[Union[str, int, bool]]
  262. # Specifies the type of input
  263. type: Var[Union[str, int, bool]]
  264. # Name of the image map used with the input
  265. use_map: Var[Union[str, int, bool]]
  266. # Value of the input
  267. value: Var[Union[str, int, float]]
  268. # Fired when the input value changes
  269. on_change: EventHandler[input_event]
  270. # Fired when the input gains focus
  271. on_focus: EventHandler[input_event]
  272. # Fired when the input loses focus
  273. on_blur: EventHandler[input_event]
  274. # Fired when a key is pressed down
  275. on_key_down: EventHandler[key_event]
  276. # Fired when a key is released
  277. on_key_up: EventHandler[key_event]
  278. class Label(BaseHTML):
  279. """Display the label element."""
  280. tag = "label"
  281. # ID of a form control with which the label is associated
  282. html_for: Var[Union[str, int, bool]]
  283. # Associates the label with a form (by id)
  284. form: Var[Union[str, int, bool]]
  285. class Legend(BaseHTML):
  286. """Display the legend element."""
  287. tag = "legend"
  288. class Meter(BaseHTML):
  289. """Display the meter element."""
  290. tag = "meter"
  291. # Associates the meter with a form (by id)
  292. form: Var[Union[str, int, bool]]
  293. # High limit of range (above this is considered high value)
  294. high: Var[Union[str, int, bool]]
  295. # Low limit of range (below this is considered low value)
  296. low: Var[Union[str, int, bool]]
  297. # Maximum value of the range
  298. max: Var[Union[str, int, bool]]
  299. # Minimum value of the range
  300. min: Var[Union[str, int, bool]]
  301. # Optimum value in the range
  302. optimum: Var[Union[str, int, bool]]
  303. # Current value of the meter
  304. value: Var[Union[str, int, bool]]
  305. class Optgroup(BaseHTML):
  306. """Display the optgroup element."""
  307. tag = "optgroup"
  308. # Disables the optgroup
  309. disabled: Var[Union[str, int, bool]]
  310. # Label for the optgroup
  311. label: Var[Union[str, int, bool]]
  312. class Option(BaseHTML):
  313. """Display the option element."""
  314. tag = "option"
  315. # Disables the option
  316. disabled: Var[Union[str, int, bool]]
  317. # Label for the option, if the text is not the label
  318. label: Var[Union[str, int, bool]]
  319. # Indicates that the option is initially selected
  320. selected: Var[Union[str, int, bool]]
  321. # Value to be sent as form data
  322. value: Var[Union[str, int, bool]]
  323. class Output(BaseHTML):
  324. """Display the output element."""
  325. tag = "output"
  326. # Associates the output with one or more elements (by their IDs)
  327. html_for: Var[Union[str, int, bool]]
  328. # Associates the output with a form (by id)
  329. form: Var[Union[str, int, bool]]
  330. # Name of the output element for form submission
  331. name: Var[Union[str, int, bool]]
  332. class Progress(BaseHTML):
  333. """Display the progress element."""
  334. tag = "progress"
  335. # Associates the progress element with a form (by id)
  336. form: Var[Union[str, int, bool]]
  337. # Maximum value of the progress indicator
  338. max: Var[Union[str, int, bool]]
  339. # Current value of the progress indicator
  340. value: Var[Union[str, int, bool]]
  341. class Select(BaseHTML):
  342. """Display the select element."""
  343. tag = "select"
  344. # Whether the form control should have autocomplete enabled
  345. auto_complete: Var[Union[str, int, bool]]
  346. # Automatically focuses the select when the page loads
  347. auto_focus: Var[Union[str, int, bool]]
  348. # Disables the select control
  349. disabled: Var[Union[str, int, bool]]
  350. # Associates the select with a form (by id)
  351. form: Var[Union[str, int, bool]]
  352. # Indicates that multiple options can be selected
  353. multiple: Var[Union[str, int, bool]]
  354. # Name of the select, used when submitting the form
  355. name: Var[Union[str, int, bool]]
  356. # Indicates that the select control must have a selected option
  357. required: Var[Union[str, int, bool]]
  358. # Number of visible options in a drop-down list
  359. size: Var[Union[str, int, bool]]
  360. # Fired when the select value changes
  361. on_change: EventHandler[input_event]
  362. AUTO_HEIGHT_JS = """
  363. const autoHeightOnInput = (e, is_enabled) => {
  364. if (is_enabled) {
  365. const el = e.target;
  366. el.style.overflowY = "scroll";
  367. el.style.height = "auto";
  368. el.style.height = (e.target.scrollHeight) + "px";
  369. if (el.form && !el.form.data_resize_on_reset) {
  370. el.form.addEventListener("reset", () => window.setTimeout(() => autoHeightOnInput(e, is_enabled), 0))
  371. el.form.data_resize_on_reset = true;
  372. }
  373. }
  374. }
  375. """
  376. ENTER_KEY_SUBMIT_JS = """
  377. const enterKeySubmitOnKeyDown = (e, is_enabled) => {
  378. if (is_enabled && e.which === 13 && !e.shiftKey) {
  379. e.preventDefault();
  380. if (!e.repeat) {
  381. if (e.target.form) {
  382. e.target.form.requestSubmit();
  383. }
  384. }
  385. }
  386. }
  387. """
  388. class Textarea(BaseHTML):
  389. """Display the textarea element."""
  390. tag = "textarea"
  391. # Whether the form control should have autocomplete enabled
  392. auto_complete: Var[Union[str, int, bool]]
  393. # Automatically focuses the textarea when the page loads
  394. auto_focus: Var[Union[str, int, bool]]
  395. # Automatically fit the content height to the text (use min-height with this prop)
  396. auto_height: Var[bool]
  397. # Visible width of the text control, in average character widths
  398. cols: Var[Union[str, int, bool]]
  399. # The default value of the textarea when initially rendered
  400. default_value: Var[str]
  401. # Name part of the textarea to submit in 'dir' and 'name' pair when form is submitted
  402. dirname: Var[Union[str, int, bool]]
  403. # Disables the textarea
  404. disabled: Var[Union[str, int, bool]]
  405. # Enter key submits form (shift-enter adds new line)
  406. enter_key_submit: Var[bool]
  407. # Associates the textarea with a form (by id)
  408. form: Var[Union[str, int, bool]]
  409. # Maximum number of characters allowed in the textarea
  410. max_length: Var[Union[str, int, bool]]
  411. # Minimum number of characters required in the textarea
  412. min_length: Var[Union[str, int, bool]]
  413. # Name of the textarea, used when submitting the form
  414. name: Var[Union[str, int, bool]]
  415. # Placeholder text in the textarea
  416. placeholder: Var[Union[str, int, bool]]
  417. # Indicates whether the textarea is read-only
  418. read_only: Var[Union[str, int, bool]]
  419. # Indicates that the textarea is required
  420. required: Var[Union[str, int, bool]]
  421. # Visible number of lines in the text control
  422. rows: Var[Union[str, int, bool]]
  423. # The controlled value of the textarea, read only unless used with on_change
  424. value: Var[Union[str, int, bool]]
  425. # How the text in the textarea is to be wrapped when submitting the form
  426. wrap: Var[Union[str, int, bool]]
  427. # Fired when the input value changes
  428. on_change: EventHandler[input_event]
  429. # Fired when the input gains focus
  430. on_focus: EventHandler[input_event]
  431. # Fired when the input loses focus
  432. on_blur: EventHandler[input_event]
  433. # Fired when a key is pressed down
  434. on_key_down: EventHandler[key_event]
  435. # Fired when a key is released
  436. on_key_up: EventHandler[key_event]
  437. @classmethod
  438. def create(cls, *children, **props):
  439. """Create a textarea component.
  440. Args:
  441. *children: The children of the textarea.
  442. **props: The properties of the textarea.
  443. Returns:
  444. The textarea component.
  445. Raises:
  446. ValueError: when `enter_key_submit` is combined with `on_key_down`.
  447. """
  448. enter_key_submit = props.get("enter_key_submit")
  449. auto_height = props.get("auto_height")
  450. custom_attrs = props.setdefault("custom_attrs", {})
  451. if enter_key_submit is not None:
  452. enter_key_submit = Var.create(enter_key_submit)
  453. if "on_key_down" in props:
  454. raise ValueError(
  455. "Cannot combine `enter_key_submit` with `on_key_down`.",
  456. )
  457. custom_attrs["on_key_down"] = Var(
  458. _js_expr=f"(e) => enterKeySubmitOnKeyDown(e, {enter_key_submit!s})",
  459. _var_data=VarData.merge(enter_key_submit._get_all_var_data()),
  460. )
  461. if auto_height is not None:
  462. auto_height = Var.create(auto_height)
  463. custom_attrs["on_input"] = Var(
  464. _js_expr=f"(e) => autoHeightOnInput(e, {auto_height!s})",
  465. _var_data=VarData.merge(auto_height._get_all_var_data()),
  466. )
  467. return super().create(*children, **props)
  468. def _exclude_props(self) -> list[str]:
  469. return [
  470. *super()._exclude_props(),
  471. "auto_height",
  472. "enter_key_submit",
  473. ]
  474. def _get_all_custom_code(self) -> Set[str]:
  475. """Include the custom code for auto_height and enter_key_submit functionality.
  476. Returns:
  477. The custom code for the component.
  478. """
  479. custom_code = super()._get_all_custom_code()
  480. if self.auto_height is not None:
  481. custom_code.add(AUTO_HEIGHT_JS)
  482. if self.enter_key_submit is not None:
  483. custom_code.add(ENTER_KEY_SUBMIT_JS)
  484. return custom_code
  485. button = Button.create
  486. datalist = Datalist.create
  487. fieldset = Fieldset.create
  488. form = Form.create
  489. input = Input.create
  490. label = Label.create
  491. legend = Legend.create
  492. meter = Meter.create
  493. optgroup = Optgroup.create
  494. option = Option.create
  495. output = Output.create
  496. progress = Progress.create
  497. select = Select.create
  498. textarea = Textarea.create