forms.py 21 KB

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