forms.py 19 KB

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