-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
78 lines (67 loc) · 1.71 KB
/
index.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
let localFetch = globalThis.fetch;
export function setFetch(fetch: typeof localFetch): void {
localFetch = fetch;
}
export default async function pushForm(
form: HTMLFormElement,
init: RequestInit = {},
): Promise<Response> {
const fields = new FormData(form);
const url = new URL(form.getAttribute('action') ?? '', location.origin);
init.headers = new Headers(init.headers);
if (!init.headers.has('Accept')) {
init.headers.append(
'Accept',
'text/html,application/xhtml+xml,application/xml',
);
}
init.method = form.method;
if (form.method === 'get') {
for (const [name, value] of fields) {
if (typeof value === 'string') {
url.searchParams.set(name, value);
}
}
} else {
init.body = fields;
init.headers.append('Cache-Control', 'max-age=0');
}
return localFetch(url.href, init);
}
interface Options {
request?: RequestInit;
onSuccess?: (r: Response) => void | Promise<void>;
onError?: (r: unknown) => void | Promise<void>;
}
function onErrorDefault(error: unknown): void {
alert('The form couldn’t be submitted');
throw error;
}
function onSuccessDefault(): void {
alert('Thanks for your submission');
}
export function ajaxifyForm(
form: HTMLFormElement,
{
onSuccess = onSuccessDefault,
onError = onErrorDefault,
request = {},
}: Options = {},
): () => void {
const submitHandler = async (event: Event) => {
event.preventDefault();
try {
const response = await pushForm(form, request);
if (!response.ok) {
throw new Error(response.statusText);
}
void onSuccess(response);
} catch (error: unknown) {
void onError(error);
}
};
form.addEventListener('submit', submitHandler);
return () => {
form.removeEventListener('submit', submitHandler);
};
}