forms.py 19 KB

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