-
Notifications
You must be signed in to change notification settings - Fork 435
/
form_interceptor.ts
36 lines (30 loc) · 1.19 KB
/
form_interceptor.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
export interface FormInterceptorDelegate {
shouldInterceptFormSubmission(element: HTMLFormElement, submitter?: HTMLElement): boolean
formSubmissionIntercepted(element: HTMLFormElement, submitter?: HTMLElement): void
}
export class FormInterceptor {
readonly delegate: FormInterceptorDelegate
readonly element: Element
constructor(delegate: FormInterceptorDelegate, element: Element) {
this.delegate = delegate
this.element = element
}
start() {
this.element.addEventListener("submit", this.submitBubbled)
}
stop() {
this.element.removeEventListener("submit", this.submitBubbled)
}
submitBubbled = <EventListener>((event: SubmitEvent) => {
const form = event.target
if (!event.defaultPrevented && form instanceof HTMLFormElement && form.closest("turbo-frame, html") == this.element) {
const submitter = event.submitter || undefined
const method = submitter?.getAttribute("formmethod") || form.method
if (method != "dialog" && this.delegate.shouldInterceptFormSubmission(form, submitter)) {
event.preventDefault()
event.stopImmediatePropagation()
this.delegate.formSubmissionIntercepted(form, submitter)
}
}
})
}