-
Notifications
You must be signed in to change notification settings - Fork 33
/
index.ts
258 lines (217 loc) · 6.16 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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
import {debounce} from '@github/mini-throttle'
type Controller = AbortController | {signal: AbortSignal | null; abort: () => void}
type State = {
check: (event: Event) => unknown
controller: Controller | null
}
const states = new WeakMap<AutoCheckElement, State>()
export default class AutoCheckElement extends HTMLElement {
connectedCallback(): void {
const input = this.input
if (!input) return
const checker = debounce(check.bind(null, this), 300)
const state = {check: checker, controller: null}
states.set(this, state)
input.addEventListener('input', setLoadingState)
input.addEventListener('input', checker)
input.autocomplete = 'off'
input.spellcheck = false
}
disconnectedCallback(): void {
const input = this.input
if (!input) return
const state = states.get(this)
if (!state) return
states.delete(this)
input.removeEventListener('input', setLoadingState)
input.removeEventListener('input', state.check)
input.setCustomValidity('')
}
attributeChangedCallback(name: string): void {
if (name === 'required') {
const input = this.input
if (!input) return
input.required = this.required
}
}
static get observedAttributes(): string[] {
return ['required']
}
get input(): HTMLInputElement | null {
return this.querySelector('input')
}
get src(): string {
const src = this.getAttribute('src')
if (!src) return ''
const link = this.ownerDocument!.createElement('a')
link.href = src
return link.href
}
set src(value: string) {
this.setAttribute('src', value)
}
get csrf(): string {
const csrfElement = this.querySelector('[data-csrf]')
return this.getAttribute('csrf') || (csrfElement instanceof HTMLInputElement && csrfElement.value) || ''
}
set csrf(value: string) {
this.setAttribute('csrf', value)
}
get required(): boolean {
return this.hasAttribute('required')
}
set required(required: boolean) {
if (required) {
this.setAttribute('required', '')
} else {
this.removeAttribute('required')
}
}
}
function setLoadingState(event: Event) {
const input = event.currentTarget
if (!(input instanceof HTMLInputElement)) return
const autoCheckElement = input.closest('auto-check')
if (!(autoCheckElement instanceof AutoCheckElement)) return
const src = autoCheckElement.src
const csrf = autoCheckElement.csrf
const state = states.get(autoCheckElement)
// If some attributes are missing we want to exit early and make sure that the element is valid.
if (!src || !csrf || !state) {
return
}
let message = 'Verifying…'
const setValidity = (text: string) => (message = text)
input.dispatchEvent(
new CustomEvent('auto-check-start', {
bubbles: true,
detail: {setValidity}
})
)
if (autoCheckElement.required) {
input.setCustomValidity(message)
}
}
function makeAbortController() {
if ('AbortController' in window) {
return new AbortController()
}
return {
signal: null,
abort() {
// Do nothing
}
}
}
async function fetchWithNetworkEvents(el: Element, url: string, options: RequestInit): Promise<Response> {
try {
const response = await fetch(url, options)
el.dispatchEvent(new CustomEvent('load'))
el.dispatchEvent(new CustomEvent('loadend'))
return response
} catch (error) {
if (error.name !== 'AbortError') {
el.dispatchEvent(new CustomEvent('error'))
el.dispatchEvent(new CustomEvent('loadend'))
}
throw error
}
}
async function check(autoCheckElement: AutoCheckElement) {
const input = autoCheckElement.input
if (!input) {
return
}
const src = autoCheckElement.src
const csrf = autoCheckElement.csrf
const state = states.get(autoCheckElement)
// If some attributes are missing we want to exit early and make sure that the element is valid.
if (!src || !csrf || !state) {
if (autoCheckElement.required) {
input.setCustomValidity('')
}
return
}
if (!input.value.trim()) {
if (autoCheckElement.required) {
input.setCustomValidity('')
}
return
}
const body = new FormData()
body.append('authenticity_token', csrf)
body.append('value', input.value)
input.dispatchEvent(
new CustomEvent('auto-check-send', {
bubbles: true,
detail: {body}
})
)
if (state.controller) {
state.controller.abort()
} else {
autoCheckElement.dispatchEvent(new CustomEvent('loadstart'))
}
state.controller = makeAbortController()
try {
const response = await fetchWithNetworkEvents(autoCheckElement, src, {
credentials: 'same-origin',
signal: state.controller.signal,
method: 'POST',
body
})
if (response.ok) {
processSuccess(response, input, autoCheckElement.required)
} else {
processFailure(response, input, autoCheckElement.required)
}
state.controller = null
input.dispatchEvent(new CustomEvent('auto-check-complete', {bubbles: true}))
} catch (error) {
if (error.name !== 'AbortError') {
state.controller = null
input.dispatchEvent(new CustomEvent('auto-check-complete', {bubbles: true}))
}
}
}
function processSuccess(response: Response, input: HTMLInputElement, required: boolean) {
if (required) {
input.setCustomValidity('')
}
input.dispatchEvent(
new CustomEvent('auto-check-success', {
bubbles: true,
detail: {
response: response.clone()
}
})
)
}
function processFailure(response: Response, input: HTMLInputElement, required: boolean) {
let message = 'Validation failed'
const setValidity = (text: string) => (message = text)
input.dispatchEvent(
new CustomEvent('auto-check-error', {
bubbles: true,
detail: {
response: response.clone(),
setValidity
}
})
)
if (required) {
input.setCustomValidity(message)
}
}
declare global {
interface Window {
AutoCheckElement: typeof AutoCheckElement
}
interface HTMLElementTagNameMap {
'auto-check': AutoCheckElement
}
}
if (!window.customElements.get('auto-check')) {
window.AutoCheckElement = AutoCheckElement
window.customElements.define('auto-check', AutoCheckElement)
}