forms.py 21 KB

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