-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
163 lines (128 loc) · 4.19 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import delegate from "delegate-it";
import { visit, navigator } from "@hotwired/turbo";
import mem from "mem";
import debounce from "lodash/debounce";
import type { Visit } from "@hotwired/turbo/dist/types/core/drive/visit";
import type { FetchRequest } from "@hotwired/turbo/dist/types/http/fetch_request";
import type { FetchResponse } from "@hotwired/turbo/dist/types/http/fetch_response";
import type { FrameController } from "@hotwired/turbo/dist/types/core/frames/frame_controller";
export type FrameElement = { delegate: FrameController } & Element;
const inflight = new Map<string, Promise<Response>>();
export const visitFrame = (response: Response, frame: FrameElement) =>
frame.delegate.requestSucceededWithResponse(
{} as FetchRequest,
{
get responseHTML() {
return response.text();
},
} as FetchResponse,
);
export const goFast = ({
keyupDebounce = 150,
onkeyup = true,
idempotentFormSelector = 'form:not([method="post"])',
anchorSelector = "a",
} = {}) => {
(["mouseover", "touchstart"] as const).forEach((event) =>
delegate(
document,
`${anchorSelector}, ${idempotentFormSelector}`,
event,
prefetch,
),
);
delegate(document, anchorSelector, "click", startVisit);
delegate(document, idempotentFormSelector, "submit", startVisit);
if (onkeyup) {
delegate(
document,
idempotentFormSelector,
"keyup",
debounce(prefetch, keyupDebounce),
);
}
/** IDEA: Preload images and SVG files on mouse down and touch start? */
};
const startVisit = (event: delegate.Event<Event, Element>) => {
if (disabled(event)) return;
const url = extractURLFrom(event.delegateTarget);
if (!url) return;
const inflightRequest = inflight.get(url);
if (!inflightRequest) return;
event.preventDefault();
const turboFrame = document.querySelector<FrameElement>(
`turbo-frame[id="${event.delegateTarget.getAttribute(
"data-turbo-frame",
)}"]`,
);
if (turboFrame) {
turboFrame.delegate.requestStarted({} as FetchRequest);
} else {
navigator.adapter.visitRequestStarted({
hasCachedSnapshot: () => false,
} as Visit);
}
inflightRequest.then((response) => {
if (turboFrame) {
visitFrame(response, turboFrame);
turboFrame.delegate.requestFinished({} as FetchRequest);
return;
}
navigator.adapter.visitRequestFinished({} as Visit);
response.text().then((responseHTML) => {
visit(url, {
response: { statusCode: response.status, responseHTML },
});
});
});
};
const memoizedFetch = mem(fetch, { maxAge: 3000, cacheKey: JSON.stringify });
export const turboFetch = (url: string, frameId: string | null) =>
memoizedFetch(url, {
credentials: "include",
headers: {
accept: "text/html, application/xhtml+xml",
...(frameId ? { "turbo-frame": frameId } : {}),
},
});
const disabled = (event: Event) =>
event.target instanceof HTMLElement &&
event.target.dataset.nitrous === "false";
const prefetch = (event: delegate.Event<Event, HTMLElement>) => {
if (disabled(event)) {
return;
}
const fullURL = extractURLFrom(event.delegateTarget);
if (!fullURL) return;
const newURL = new URL(fullURL);
if (newURL.hostname !== window.location.hostname) {
return;
}
const urlWithoutHash =
window.location.origin + newURL.pathname + newURL.search;
if (inflight.has(urlWithoutHash)) return;
const turboFrameId = event.delegateTarget.getAttribute("data-turbo-frame");
const request = turboFetch(urlWithoutHash, turboFrameId);
request.then((response) => {
if (!response.headers.get("Cache-Control")?.includes("max-age")) {
console.warn(
`Pre-fetched response from ${response.url} should include max-age.`,
);
}
});
inflight.set(
urlWithoutHash,
request.finally(() => {
inflight.delete(urlWithoutHash);
}),
);
};
export const extractURLFrom = (target: EventTarget | null) => {
if (target instanceof HTMLAnchorElement) {
return target.href;
} else if (target instanceof HTMLFormElement) {
const url = new URL(target.action);
url.search = new URLSearchParams(new FormData(target) as any).toString();
return url.toString();
}
};