Skip to content

Commit 6149b0d

Browse files
committed
🏷️ Improve types of getInput and flexibility of update for useForm
1 parent 1793202 commit 6149b0d

1 file changed

Lines changed: 10 additions & 5 deletions

File tree

src/blocks/Form/useForm.ts

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,15 @@
22
import { get } from 'webcoreui'
33

44
export type ValidationFactory = (formValues: Record<string, string>) => Record<string, boolean>
5+
export type FormField = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | HTMLButtonElement
56

67
export type FormActions = {
78
validationRules: Record<string, boolean>
89
validationFactory: ValidationFactory | null
910
isPreventDefault: boolean
1011
onErrorCallback: ((invalidFields: string[]) => void) | null
1112
preventDefault: () => FormActions
12-
getInput: (field: string) => HTMLInputElement | null
13+
getInput: (field: string) => FormField | null
1314
getInputValue: (field: string) => string | null
1415
getInputValues: () => Record<string, string>
1516
update: (field: string, value: string | boolean) => FormActions
@@ -73,7 +74,7 @@ export const useForm = (selector: string | HTMLFormElement | null | undefined):
7374
return this
7475
},
7576
getInput(field) {
76-
return form.querySelector(`[name=${field}]`)
77+
return form.querySelector<FormField>(`[name=${field}]`)
7778
},
7879
getInputValue(field) {
7980
const value = new FormData(form).get(field)
@@ -91,7 +92,7 @@ export const useForm = (selector: string | HTMLFormElement | null | undefined):
9192
return formValues
9293
},
9394
update(field, value) {
94-
const input = form.querySelector(`[name=${field}]`) as HTMLInputElement
95+
const input = form.querySelector<FormField>(`[name=${field}]`)
9596

9697
if (!input) {
9798
// eslint-disable-next-line no-console
@@ -100,12 +101,16 @@ export const useForm = (selector: string | HTMLFormElement | null | undefined):
100101
return this
101102
}
102103

103-
if (typeof value === 'boolean') {
104+
if ('checked' in input && typeof value === 'boolean') {
104105
input.checked = value
105106
}
106107

107108
if (typeof value === 'string') {
108-
input.value = value
109+
if (input instanceof HTMLButtonElement) {
110+
input.textContent = value
111+
} else {
112+
input.value = value
113+
}
109114
}
110115

111116
return this

0 commit comments

Comments
 (0)