forms.py 20 KB

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