-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathtext-expander-element.ts
More file actions
322 lines (262 loc) · 9.16 KB
/
text-expander-element.ts
File metadata and controls
322 lines (262 loc) · 9.16 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
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
import Combobox from '@github/combobox-nav'
import query from './query'
import {InputRange} from 'dom-input-range'
export type TextExpanderMatch = {
text: string
key: string
position: number
}
export type TextExpanderResult = {
fragment?: HTMLElement
matched: boolean
}
export type TextExpanderKey = {
key: string
multiWord: boolean
}
export type TextExpanderChangeEvent = Event & {
detail?: {
key: string
text: string
provide: (result: Promise<TextExpanderResult> | TextExpanderResult) => void
}
}
const states = new WeakMap()
class TextExpander {
expander: TextExpanderElement
input: HTMLInputElement | HTMLTextAreaElement
menu: HTMLElement | null
oninput: (event: Event) => void
onkeydown: (event: KeyboardEvent) => void
onpaste: (event: Event) => void
oncommit: (event: Event) => void
onblur: (event: Event) => void
onmousedown: (event: Event) => void
combobox: Combobox | null
match: TextExpanderMatch | null
justPasted: boolean
lookBackIndex: number
interactingWithList: boolean
constructor(expander: TextExpanderElement, input: HTMLInputElement | HTMLTextAreaElement) {
this.expander = expander
this.input = input
this.combobox = null
this.menu = null
this.match = null
this.justPasted = false
this.lookBackIndex = 0
this.oninput = this.onInput.bind(this)
this.onpaste = this.onPaste.bind(this)
this.onkeydown = this.onKeydown.bind(this)
this.oncommit = this.onCommit.bind(this)
this.onmousedown = this.onMousedown.bind(this)
this.onblur = this.onBlur.bind(this)
this.interactingWithList = false
input.addEventListener('paste', this.onpaste)
input.addEventListener('input', this.oninput)
;(input as HTMLElement).addEventListener('keydown', this.onkeydown)
input.addEventListener('blur', this.onblur)
}
destroy() {
this.input.removeEventListener('paste', this.onpaste)
this.input.removeEventListener('input', this.oninput)
;(this.input as HTMLElement).removeEventListener('keydown', this.onkeydown)
this.input.removeEventListener('blur', this.onblur)
}
dismissMenu() {
if (this.deactivate()) {
this.lookBackIndex = this.input.selectionEnd || this.lookBackIndex
}
}
private activate(match: TextExpanderMatch, menu: HTMLElement) {
if (this.input !== document.activeElement && this.input !== document.activeElement?.shadowRoot?.activeElement) {
return
}
this.deactivate()
this.menu = menu
if (!menu.id) menu.id = `text-expander-${Math.floor(Math.random() * 100000).toString()}`
this.expander.append(menu)
this.combobox = new Combobox(this.input, menu)
this.expander.dispatchEvent(new Event('text-expander-activate'))
this.positionMenu(menu, match.position)
this.combobox.start()
menu.addEventListener('combobox-commit', this.oncommit)
menu.addEventListener('mousedown', this.onmousedown)
// Focus first menu item.
this.combobox.navigate(1)
}
private positionMenu(menu: HTMLElement, position: number) {
// Clamp position to valid range to avoid IndexSizeError when input text changes
const clampedPosition = Math.min(position, this.input.value.length)
const caretRect = new InputRange(this.input, clampedPosition).getBoundingClientRect()
const targetPosition = {left: caretRect.left, top: caretRect.top + caretRect.height}
const currentPosition = menu.getBoundingClientRect()
const delta = {
left: targetPosition.left - currentPosition.left,
top: targetPosition.top - currentPosition.top
}
if (delta.left !== 0 || delta.top !== 0) {
// Use computedStyle to avoid nesting calc() deeper and deeper
const currentStyle = getComputedStyle(menu)
// Using `calc` avoids having to parse the current pixel value
menu.style.left = currentStyle.left ? `calc(${currentStyle.left} + ${delta.left}px)` : `${delta.left}px`
menu.style.top = currentStyle.top ? `calc(${currentStyle.top} + ${delta.top}px)` : `${delta.top}px`
}
}
private deactivate() {
const menu = this.menu
if (!menu || !this.combobox) return false
this.expander.dispatchEvent(new Event('text-expander-deactivate'))
this.menu = null
menu.removeEventListener('combobox-commit', this.oncommit)
menu.removeEventListener('mousedown', this.onmousedown)
this.combobox.destroy()
this.combobox = null
menu.remove()
return true
}
private onCommit({target}: Event) {
const item = target
if (!(item instanceof HTMLElement)) return
if (!this.combobox) return
const match = this.match
if (!match) return
const beginning = this.input.value.substring(0, match.position - match.key.length)
const remaining = this.input.value.substring(match.position + match.text.length)
const detail = {item, key: match.key, value: null, continue: false}
const canceled = !this.expander.dispatchEvent(new CustomEvent('text-expander-value', {cancelable: true, detail}))
if (canceled) return
if (!detail.value) return
let suffix = this.expander.getAttribute('suffix') ?? ' '
if (detail.continue) {
suffix = ''
}
const value = `${detail.value}${suffix}`
this.input.value = beginning + value + remaining
const cursor = beginning.length + value.length
this.deactivate()
this.input.focus({
preventScroll: true
})
this.input.selectionStart = cursor
this.input.selectionEnd = cursor
if (!detail.continue) {
this.lookBackIndex = cursor
this.match = null
}
this.expander.dispatchEvent(
new CustomEvent('text-expander-committed', {cancelable: false, detail: {input: this.input}})
)
}
private onBlur() {
if (this.interactingWithList) {
this.interactingWithList = false
return
}
this.deactivate()
}
private onPaste() {
this.justPasted = true
}
private isMatchStillValid(match: TextExpanderMatch): boolean {
return match.position <= this.input.value.length
}
async onInput() {
if (this.justPasted) {
this.justPasted = false
return
}
const match = this.findMatch()
if (match) {
this.match = match
const menu = await this.notifyProviders(match)
// Text was cleared while waiting on async providers.
if (!this.match || !this.isMatchStillValid(match)) {
this.match = null
this.deactivate()
return
}
if (menu) {
this.activate(match, menu)
} else {
this.deactivate()
}
} else {
this.match = null
this.deactivate()
}
}
findMatch(): TextExpanderMatch | void {
const cursor = this.input.selectionEnd || 0
const text = this.input.value
if (cursor <= this.lookBackIndex) {
this.lookBackIndex = cursor - 1
}
for (const {key, multiWord} of this.expander.keys) {
const found = query(text, key, cursor, {
multiWord,
lookBackIndex: this.lookBackIndex,
lastMatchPosition: this.match ? this.match.position : null
})
if (found) {
return {text: found.text, key, position: found.position}
}
}
}
async notifyProviders(match: TextExpanderMatch): Promise<HTMLElement | void> {
const providers: Array<Promise<TextExpanderResult> | TextExpanderResult> = []
const provide = (result: Promise<TextExpanderResult> | TextExpanderResult) => providers.push(result)
const changeEvent = new CustomEvent('text-expander-change', {
cancelable: true,
detail: {provide, text: match.text, key: match.key}
}) as TextExpanderChangeEvent
const canceled = !this.expander.dispatchEvent(changeEvent)
if (canceled) return
const all = await Promise.all(providers)
const fragments = all.filter(x => x.matched).map(x => x.fragment)
return fragments[0]
}
private onMousedown() {
this.interactingWithList = true
}
private onKeydown(event: KeyboardEvent) {
if (event.key === 'Escape') {
this.match = null
if (this.deactivate()) {
this.lookBackIndex = this.input.selectionEnd || this.lookBackIndex
event.stopImmediatePropagation()
event.preventDefault()
}
}
}
}
export default class TextExpanderElement extends HTMLElement {
get keys(): TextExpanderKey[] {
const keysAttr = this.getAttribute('keys')
const keys = keysAttr ? keysAttr.split(' ') : []
const multiWordAttr = this.getAttribute('multiword')
const multiWord = multiWordAttr ? multiWordAttr.split(' ') : []
const globalMultiWord = multiWord.length === 0 && this.hasAttribute('multiword')
return keys.map(key => ({key, multiWord: globalMultiWord || multiWord.includes(key)}))
}
set keys(value: string) {
this.setAttribute('keys', value)
}
connectedCallback(): void {
const input = this.querySelector('input[type="text"], textarea')
if (!(input instanceof HTMLInputElement || input instanceof HTMLTextAreaElement)) return
const state = new TextExpander(this, input)
states.set(this, state)
}
disconnectedCallback(): void {
const state: TextExpander = states.get(this)
if (!state) return
state.destroy()
states.delete(this)
}
dismiss(): void {
const state: TextExpander = states.get(this)
if (!state) return
state.dismissMenu()
}
}