Skip to content
Source
Sign inSign up
TanStack/form
Open History to see the last commit

index.ts

106 lines2.5 KB

1import { LitElement, html } from 'lit'
2import { customElement } from 'lit/decorators.js'
3import { TanStackFormController } from '@tanstack/lit-form'
4import {
5 step1Schema,
6 step2Schema,
7 stepValidator,
8 wizardFormOptions,
9} from './shared-form'
10import { textField } from './text-field'
11import './styles.css'
12​
13@customElement('tanstack-form-wizard')
14export class TanStackFormWizard extends LitElement {
15 private step = 0
16 private form = new TanStackFormController(this, {
17 ...wizardFormOptions,
18 onSubmit: ({ value }) => {
19 alert(`Form submitted: ${JSON.stringify(value)}`)
20 },
21 })
22​
23 protected createRenderRoot() {
24 return this
25 }
26​
27 render() {
28 return html`
29 <h1>Multi-step Wizard</h1>
30 ${this.step === 0 ? this.renderStepOne() : this.renderStepTwo()}
31 `
32 }
33​
34 private renderStepOne() {
35 return this.form.formGroup(
36 {
37 name: 'step1',
38 validators: [stepValidator(step1Schema)],
39 onSubmit: () => {
40 this.step = 1
41 this.requestUpdate()
42 },
43 },
44 (group) => html`
45 <form
46 @submit=${(event: SubmitEvent) => {
47 event.preventDefault()
48 event.stopPropagation()
49 void group.handleSubmit()
50 }}
51 >
52 ${group.field({ name: 'name' }, (field) =>
53 textField(field, 'Step 1 Name'),
54 )}
55 ${this.submitButton('Next')}
56 </form>
57 `,
58 )
59 }
60​
61 private renderStepTwo() {
62 return this.form.formGroup(
63 {
64 name: 'step2',
65 validators: [stepValidator(step2Schema)],
66 onSubmit: () => {
67 void this.form.api.handleSubmit()
68 },
69 },
70 (group) => html`
71 <form
72 @submit=${(event: SubmitEvent) => {
73 event.preventDefault()
74 event.stopPropagation()
75 void group.handleSubmit()
76 }}
77 >
78 ${group.field({ name: 'name' }, (field) =>
79 textField(field, 'Step 2 Name'),
80 )}
81 <div class="actions">
82 <button
83 type="button"
84 @click=${() => {
85 this.step = 0
86 this.requestUpdate()
87 }}
88 >
89 Back
90 </button>
91 ${this.submitButton('Submit')}
92 </div>
93 </form>
94 `,
95 )
96 }
97​
98 private submitButton(label: string) {
99 return this.form.subscribe(
100 (state) => state.isSubmitting,
101 (isSubmitting) => html`
102 <button type="submit" ?disabled=${isSubmitting}>${label}</button>
103 `,
104 )
105 }