forms.py 19 KB

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