1
0

forms.py 19 KB

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