forms.py 21 KB

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