forms.py 20 KB

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