forms.py 20 KB

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