forms.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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
  10. from reflex.utils import imports
  11. from reflex.utils.format import format_event_chain
  12. from reflex.vars import BaseVar, Var
  13. from .base import BaseHTML
  14. FORM_DATA = Var.create("form_data")
  15. HANDLE_SUBMIT_JS_JINJA2 = Environment().from_string(
  16. """
  17. const handleSubmit_{{ handle_submit_unique_name }} = useCallback((ev) => {
  18. const $form = ev.target
  19. ev.preventDefault()
  20. const {{ form_data }} = {...Object.fromEntries(new FormData($form).entries()), ...{{ field_ref_mapping }}}
  21. {{ on_submit_event_chain }}
  22. if ({{ reset_on_submit }}) {
  23. $form.reset()
  24. }
  25. })
  26. """
  27. )
  28. class Button(BaseHTML):
  29. """Display the button element."""
  30. tag = "button"
  31. # Automatically focuses the button when the page loads
  32. auto_focus: Var[Union[str, int, bool]]
  33. # Disables the button
  34. disabled: Var[bool]
  35. # Associates the button with a form (by id)
  36. form: Var[Union[str, int, bool]]
  37. # URL to send the form data to (for type="submit" buttons)
  38. form_action: Var[Union[str, int, bool]]
  39. # How the form data should be encoded when submitting to the server (for type="submit" buttons)
  40. form_enc_type: Var[Union[str, int, bool]]
  41. # HTTP method to use for sending form data (for type="submit" buttons)
  42. form_method: Var[Union[str, int, bool]]
  43. # Bypasses form validation when submitting (for type="submit" buttons)
  44. form_no_validate: Var[Union[str, int, bool]]
  45. # Specifies where to display the response after submitting the form (for type="submit" buttons)
  46. form_target: Var[Union[str, int, bool]]
  47. # Name of the button, used when sending form data
  48. name: Var[Union[str, int, bool]]
  49. # Type of the button (submit, reset, or button)
  50. type: Var[Union[str, int, bool]]
  51. # Value of the button, used when sending form data
  52. value: Var[Union[str, int, bool]]
  53. class Datalist(BaseHTML):
  54. """Display the datalist element."""
  55. tag = "datalist"
  56. # No unique attributes, only common ones are inherited
  57. class Fieldset(Element):
  58. """Display the fieldset element."""
  59. tag = "fieldset"
  60. # Disables all the form control descendants of the fieldset
  61. disabled: Var[Union[str, int, bool]]
  62. # Associates the fieldset with a form (by id)
  63. form: Var[Union[str, int, bool]]
  64. # Name of the fieldset, used for scripting
  65. name: Var[Union[str, int, bool]]
  66. class Form(BaseHTML):
  67. """Display the form element."""
  68. tag = "form"
  69. # MIME types the server accepts for file upload
  70. accept: Var[Union[str, int, bool]]
  71. # Character encodings to be used for form submission
  72. accept_charset: Var[Union[str, int, bool]]
  73. # URL where the form's data should be submitted
  74. action: Var[Union[str, int, bool]]
  75. # Whether the form should have autocomplete enabled
  76. auto_complete: Var[Union[str, int, bool]]
  77. # Encoding type for the form data when submitted
  78. enc_type: Var[Union[str, int, bool]]
  79. # HTTP method to use for form submission
  80. method: Var[Union[str, int, bool]]
  81. # Name of the form
  82. name: Var[Union[str, int, bool]]
  83. # Indicates that the form should not be validated on submit
  84. no_validate: Var[Union[str, int, bool]]
  85. # Where to display the response after submitting the form
  86. target: Var[Union[str, int, bool]]
  87. # If true, the form will be cleared after submit.
  88. reset_on_submit: Var[bool] = False # type: ignore
  89. # The name used to make this form's submit handler function unique.
  90. handle_submit_unique_name: Var[str]
  91. def get_event_triggers(self) -> Dict[str, Any]:
  92. """Event triggers for radix form root.
  93. Returns:
  94. The triggers for event supported by Root.
  95. """
  96. return {
  97. **super().get_event_triggers(),
  98. EventTriggers.ON_SUBMIT: lambda e0: [FORM_DATA],
  99. }
  100. @classmethod
  101. def create(cls, *children, **props):
  102. """Create a form component.
  103. Args:
  104. *children: The children of the form.
  105. **props: The properties of the form.
  106. Returns:
  107. The form component.
  108. """
  109. if "handle_submit_unique_name" in props:
  110. return super().create(*children, **props)
  111. # Render the form hooks and use the hash of the resulting code to create a unique name.
  112. props["handle_submit_unique_name"] = ""
  113. form = super().create(*children, **props)
  114. form.handle_submit_unique_name = md5(
  115. str({**form.get_hooks_internal(), **form.get_hooks()}).encode("utf-8")
  116. ).hexdigest()
  117. return form
  118. def _get_imports(self) -> imports.ImportDict:
  119. return imports.merge_imports(
  120. super()._get_imports(),
  121. {
  122. "react": {imports.ImportVar(tag="useCallback")},
  123. f"/{Dirs.STATE_PATH}": {
  124. imports.ImportVar(tag="getRefValue"),
  125. imports.ImportVar(tag="getRefValues"),
  126. },
  127. },
  128. )
  129. def _get_hooks(self) -> str | None:
  130. if EventTriggers.ON_SUBMIT not in self.event_triggers:
  131. return
  132. return HANDLE_SUBMIT_JS_JINJA2.render(
  133. handle_submit_unique_name=self.handle_submit_unique_name,
  134. form_data=FORM_DATA,
  135. field_ref_mapping=str(Var.create_safe(self._get_form_refs())),
  136. on_submit_event_chain=format_event_chain(
  137. self.event_triggers[EventTriggers.ON_SUBMIT]
  138. ),
  139. reset_on_submit=self.reset_on_submit,
  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: BaseVar(
  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_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 = Var.create_safe(ref[:-3]).as_ref()
  161. form_refs[ref[5:-3]] = Var.create_safe(
  162. f"getRefValues({str(ref_var)})", _var_is_local=False
  163. )._replace(merge_var_data=ref_var._var_data)
  164. else:
  165. ref_var = Var.create_safe(ref).as_ref()
  166. form_refs[ref[4:]] = Var.create_safe(
  167. f"getRefValue({str(ref_var)})", _var_is_local=False
  168. )._replace(merge_var_data=ref_var._var_data)
  169. return form_refs
  170. def _get_vars(self, include_children: bool = True) -> Iterator[Var]:
  171. yield from super()._get_vars(include_children=include_children)
  172. yield from self._get_form_refs().values()
  173. def _exclude_props(self) -> list[str]:
  174. return super()._exclude_props() + [
  175. "reset_on_submit",
  176. "handle_submit_unique_name",
  177. ]
  178. class Input(BaseHTML):
  179. """Display the input element."""
  180. tag = "input"
  181. # Accepted types of files when the input is file type
  182. accept: Var[Union[str, int, bool]]
  183. # Alternate text for input type="image"
  184. alt: Var[Union[str, int, bool]]
  185. # Whether the input should have autocomplete enabled
  186. auto_complete: Var[Union[str, int, bool]]
  187. # Automatically focuses the input when the page loads
  188. auto_focus: Var[Union[str, int, bool]]
  189. # Captures media from the user (camera or microphone)
  190. capture: Var[Union[str, int, bool]]
  191. # Indicates whether the input is checked (for checkboxes and radio buttons)
  192. checked: Var[Union[str, int, bool]]
  193. # The initial value (for checkboxes and radio buttons)
  194. default_checked: Var[bool]
  195. # The initial value for a text field
  196. default_value: Var[str]
  197. # Name part of the input to submit in 'dir' and 'name' pair when form is submitted
  198. dirname: Var[Union[str, int, bool]]
  199. # Disables the input
  200. disabled: Var[Union[str, int, bool]]
  201. # Associates the input with a form (by id)
  202. form: Var[Union[str, int, bool]]
  203. # URL to send the form data to (for type="submit" buttons)
  204. form_action: Var[Union[str, int, bool]]
  205. # How the form data should be encoded when submitting to the server (for type="submit" buttons)
  206. form_enc_type: Var[Union[str, int, bool]]
  207. # HTTP method to use for sending form data (for type="submit" buttons)
  208. form_method: Var[Union[str, int, bool]]
  209. # Bypasses form validation when submitting (for type="submit" buttons)
  210. form_no_validate: Var[Union[str, int, bool]]
  211. # Specifies where to display the response after submitting the form (for type="submit" buttons)
  212. form_target: Var[Union[str, int, bool]]
  213. # References a datalist for suggested options
  214. list: Var[Union[str, int, bool]]
  215. # Specifies the maximum value for the input
  216. max: Var[Union[str, int, bool]]
  217. # Specifies the maximum number of characters allowed in the input
  218. max_length: Var[Union[str, int, bool]]
  219. # Specifies the minimum number of characters required in the input
  220. min_length: Var[Union[str, int, bool]]
  221. # Specifies the minimum value for the input
  222. min: Var[Union[str, int, bool]]
  223. # Indicates whether multiple values can be entered in an input of the type email or file
  224. multiple: Var[Union[str, int, bool]]
  225. # Name of the input, used when sending form data
  226. name: Var[Union[str, int, bool]]
  227. # Regex pattern the input's value must match to be valid
  228. pattern: Var[Union[str, int, bool]]
  229. # Placeholder text in the input
  230. placeholder: Var[Union[str, int, bool]]
  231. # Indicates whether the input is read-only
  232. read_only: Var[Union[str, int, bool]]
  233. # Indicates that the input is required
  234. required: Var[Union[str, int, bool]]
  235. # Specifies the visible width of a text control
  236. size: Var[Union[str, int, bool]]
  237. # URL for image inputs
  238. src: Var[Union[str, int, bool]]
  239. # Specifies the legal number intervals for an input
  240. step: Var[Union[str, int, bool]]
  241. # Specifies the type of input
  242. type: Var[Union[str, int, bool]]
  243. # Name of the image map used with the input
  244. use_map: Var[Union[str, int, bool]]
  245. # Value of the input
  246. value: Var[Union[str, int, bool]]
  247. def get_event_triggers(self) -> Dict[str, Any]:
  248. """Get the event triggers that pass the component's value to the handler.
  249. Returns:
  250. A dict mapping the event trigger to the var that is passed to the handler.
  251. """
  252. return {
  253. **super().get_event_triggers(),
  254. EventTriggers.ON_CHANGE: lambda e0: [e0.target.value],
  255. EventTriggers.ON_FOCUS: lambda e0: [e0.target.value],
  256. EventTriggers.ON_BLUR: lambda e0: [e0.target.value],
  257. EventTriggers.ON_KEY_DOWN: lambda e0: [e0.key],
  258. EventTriggers.ON_KEY_UP: lambda e0: [e0.key],
  259. }
  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. def get_event_triggers(self) -> Dict[str, Any]:
  344. """Get the event triggers that pass the component's value to the handler.
  345. Returns:
  346. A dict mapping the event trigger to the var that is passed to the handler.
  347. """
  348. return {
  349. **super().get_event_triggers(),
  350. EventTriggers.ON_CHANGE: lambda e0: [e0.target.value],
  351. }
  352. AUTO_HEIGHT_JS = """
  353. const autoHeightOnInput = (e, is_enabled) => {
  354. if (is_enabled) {
  355. const el = e.target;
  356. el.style.overflowY = "hidden";
  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. def _exclude_props(self) -> list[str]:
  416. return super()._exclude_props() + [
  417. "auto_height",
  418. "enter_key_submit",
  419. ]
  420. def get_custom_code(self) -> Set[str]:
  421. """Include the custom code for auto_height and enter_key_submit functionality.
  422. Returns:
  423. The custom code for the component.
  424. """
  425. custom_code = super().get_custom_code()
  426. if self.auto_height is not None:
  427. custom_code.add(AUTO_HEIGHT_JS)
  428. if self.enter_key_submit is not None:
  429. custom_code.add(ENTER_KEY_SUBMIT_JS)
  430. return custom_code
  431. def _render(self) -> Tag:
  432. tag = super()._render()
  433. if self.enter_key_submit is not None:
  434. if "on_key_down" in self.event_triggers:
  435. raise ValueError(
  436. "Cannot combine `enter_key_submit` with `on_key_down`.",
  437. )
  438. tag.add_props(
  439. on_key_down=Var.create_safe(
  440. f"(e) => enterKeySubmitOnKeyDown(e, {self.enter_key_submit._var_name_unwrapped})",
  441. _var_is_local=False,
  442. )._replace(merge_var_data=self.enter_key_submit._var_data),
  443. )
  444. if self.auto_height is not None:
  445. tag.add_props(
  446. on_input=Var.create_safe(
  447. f"(e) => autoHeightOnInput(e, {self.auto_height._var_name_unwrapped})",
  448. _var_is_local=False,
  449. )._replace(merge_var_data=self.auto_height._var_data),
  450. )
  451. return tag
  452. def get_event_triggers(self) -> Dict[str, Any]:
  453. """Get the event triggers that pass the component's value to the handler.
  454. Returns:
  455. A dict mapping the event trigger to the var that is passed to the handler.
  456. """
  457. return {
  458. **super().get_event_triggers(),
  459. EventTriggers.ON_CHANGE: lambda e0: [e0.target.value],
  460. EventTriggers.ON_FOCUS: lambda e0: [e0.target.value],
  461. EventTriggers.ON_BLUR: lambda e0: [e0.target.value],
  462. EventTriggers.ON_KEY_DOWN: lambda e0: [e0.key],
  463. EventTriggers.ON_KEY_UP: lambda e0: [e0.key],
  464. }