forms.py 19 KB

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