forms.py 20 KB

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