-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathauto-complete-element.ts
More file actions
191 lines (160 loc) · 5.08 KB
/
auto-complete-element.ts
File metadata and controls
191 lines (160 loc) · 5.08 KB
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
import Autocomplete from './autocomplete.js'
const HTMLElement = globalThis.HTMLElement || (null as unknown as (typeof window)['HTMLElement'])
type AutoCompleteEventInit = EventInit & {
relatedTarget: HTMLInputElement
}
export class AutoCompleteEvent extends Event {
relatedTarget: HTMLInputElement
constructor(type: 'auto-complete-change', {relatedTarget, ...init}: AutoCompleteEventInit) {
super(type, init)
this.relatedTarget = relatedTarget
}
}
const state = new WeakMap()
export interface CSPTrustedTypesPolicy {
createHTML: (s: string, response: Response) => CSPTrustedHTMLToStringable
}
// Note: basically every object (and some primitives) in JS satisfy this
// `CSPTrustedHTMLToStringable` interface, but this is the most compatible shape
// we can use.
interface CSPTrustedHTMLToStringable {
toString: () => string
}
let cspTrustedTypesPolicyPromise: Promise<CSPTrustedTypesPolicy> | null = null
export class AutoCompleteElement extends HTMLElement {
static define(tag = 'auto-complete', registry = customElements) {
registry.define(tag, this)
return this
}
static setCSPTrustedTypesPolicy(policy: CSPTrustedTypesPolicy | Promise<CSPTrustedTypesPolicy> | null): void {
cspTrustedTypesPolicyPromise = policy === null ? policy : Promise.resolve(policy)
}
#forElement: HTMLElement | null = null
get forElement(): HTMLElement | null {
if (this.#forElement?.isConnected) {
return this.#forElement
}
const id = this.getAttribute('for')
const root = this.getRootNode()
if (id && (root instanceof Document || root instanceof ShadowRoot)) {
return root.getElementById(id)
}
return null
}
set forElement(element: HTMLElement | null) {
this.#forElement = element
this.setAttribute('for', '')
}
#inputElement: HTMLInputElement | null = null
get inputElement(): HTMLInputElement | null {
if (this.#inputElement?.isConnected) {
return this.#inputElement
}
return this.querySelector<HTMLInputElement>('input')
}
set inputElement(input: HTMLInputElement | null) {
this.#inputElement = input
this.#reattachState()
}
connectedCallback(): void {
if (!this.isConnected) return
this.#reattachState()
new MutationObserver(() => {
if (!state.get(this)) {
this.#reattachState()
}
}).observe(this, {subtree: true, childList: true})
}
disconnectedCallback(): void {
const autocomplete = state.get(this)
if (autocomplete) {
autocomplete.destroy()
state.delete(this)
}
}
#reattachState() {
state.get(this)?.destroy()
const {forElement, inputElement} = this
if (!forElement || !inputElement) return
const autoselectEnabled = this.getAttribute('data-autoselect') === 'true'
state.set(this, new Autocomplete(this, inputElement, forElement, autoselectEnabled))
forElement.setAttribute('role', 'listbox')
}
get src(): string {
return this.getAttribute('src') || ''
}
set src(url: string) {
this.setAttribute('src', url)
}
get value(): string {
return this.getAttribute('value') || ''
}
set value(value: string) {
this.setAttribute('value', value)
}
get open(): boolean {
return this.hasAttribute('open')
}
set open(value: boolean) {
if (value) {
this.setAttribute('open', '')
} else {
this.removeAttribute('open')
}
}
// HEAD
get fetchOnEmpty(): boolean {
return this.hasAttribute('fetch-on-empty')
}
set fetchOnEmpty(fetchOnEmpty: boolean) {
this.toggleAttribute('fetch-on-empty', fetchOnEmpty)
}
#requestController?: AbortController
async fetchResult(url: URL): Promise<string | CSPTrustedHTMLToStringable> {
this.#requestController?.abort()
const {signal} = (this.#requestController = new AbortController())
const res = await fetch(url.toString(), {
signal,
headers: {
Accept: 'text/fragment+html',
},
})
if (!res.ok) {
throw new Error(await res.text())
}
if (cspTrustedTypesPolicyPromise) {
const cspTrustedTypesPolicy = await cspTrustedTypesPolicyPromise
return cspTrustedTypesPolicy.createHTML(await res.text(), res)
}
return await res.text()
}
//f21528e (add csp trusted types policy)
static get observedAttributes(): string[] {
return ['open', 'value', 'for']
}
attributeChangedCallback(name: string, oldValue: string, newValue: string): void {
if (oldValue === newValue) return
const autocomplete = state.get(this)
if (!autocomplete) return
if (this.forElement !== state.get(this)?.results || this.inputElement !== state.get(this)?.input) {
this.#reattachState()
}
switch (name) {
case 'open':
newValue === null ? autocomplete.close() : autocomplete.open()
break
case 'value':
if (newValue !== null) {
autocomplete.input.value = newValue
}
this.dispatchEvent(
new AutoCompleteEvent('auto-complete-change', {
bubbles: true,
relatedTarget: autocomplete.input,
}),
)
break
}
}
}
export default AutoCompleteElement