-
Notifications
You must be signed in to change notification settings - Fork 185
/
TabCompletion.tsx
496 lines (430 loc) · 16.9 KB
/
TabCompletion.tsx
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
/*
* Copyright 2020 The Kubernetes Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eslint-disable @typescript-eslint/no-use-before-define */
import Debug from 'debug'
import React from 'react'
import minimist from 'yargs-parser'
import {
CompletionResponse,
typeahead,
findCompletions as findCompletionsFromRegistrar
} from '@kui-shell/core/mdist/api/TabCompletion'
import { getCurrentTab } from '@kui-shell/core/mdist/api/Tab'
import { _split, Split } from '@kui-shell/core/mdist/api/Exec'
import Button from '../../../spi/Button'
import { InputElement, InputProvider as Input } from './Input'
import '../../../../../web/css/static/TabCompletion.scss'
const debug = Debug('Terminal/Input/TabCompletion')
/** Escape the given string for bash happiness */
const shellescape = (str: string): string => {
return str.replace(/ /g, '\\ ')
}
/** Ibid, but only escape if the given prefix does not end with a backslash escape */
function shellescapeIfNeeded(str: string, prefix: string, shellEscapeNotNeeded: boolean): string {
return shellEscapeNotNeeded ? str : prefix.charAt(prefix.length - 1) === '\\' ? str : shellescape(str)
}
/** User has typed `partial`, and we have `completions` to offer them. */
interface Completions {
partial: string
shellEscapeNotNeeded?: boolean
completions: CompletionResponse[]
}
/**
* Abstract base class to manage Tab Completion state. This includes
* asynchronously enumerating the `completions` from a starting
* `partial. Subclasses will handle both rendering of completion
* results, and also will direct state transitions.
*
*/
export abstract class TabCompletionState {
private currentEnumeratorAsync: ReturnType<typeof setTimeout>
protected readonly lastIdx: number
public constructor(protected readonly input: Input) {
debug('tab completion init')
// remember where the cursor was when the user hit tab
this.lastIdx = this.input.state.prompt.selectionEnd
}
private findCommandCompletions(last: string) {
return typeahead(last)
}
protected async findCompletions(lastIdx = this.input.state.prompt.selectionEnd) {
const input = this.input
const { prompt } = this.input.state
const { A: argv, endIndices } = _split(prompt.value, true, true) as Split
const options = minimist(argv)
const toBeCompletedIdx = endIndices.findIndex(idx => idx >= lastIdx) // e.g. git branch f<tab>
const completingTrailingEmpty = lastIdx > endIndices[endIndices.length - 1] // e.g. git branch <tab>
if (toBeCompletedIdx >= 0 || completingTrailingEmpty) {
// trim beginning only; e.g. `ls /tmp/mo\ ` <-- we need that trailing space
const last = completingTrailingEmpty
? ''
: prompt.value.substring(endIndices[toBeCompletedIdx - 1], lastIdx).replace(/^\s+/, '')
const commandCompletions = this.findCommandCompletions(prompt.value)
if (commandCompletions && commandCompletions.length > 0) {
return { partial: last, completions: commandCompletions, shellEscapeNotNeeded: true }
}
// argvNoOptions is argv without the options; we can get
// this directly from yargs-parser's '_'
const argvNoOptions = options._.map(_ => _.toString())
const parsedOptions = Object.assign({}, options, { _: undefined })
delete parsedOptions._
// a parsed out version of the command line
const commandLine = {
command: prompt.value,
argv,
argvNoOptions,
parsedOptions
}
// a specification of what we want to be completed
const spec = {
toBeCompletedIdx, // index into argv
toBeCompleted: last.replace(/\\ /, ' ').replace(/\\$/, '') // how much of that argv has been filled in so far
}
return new Promise<Completions>(resolve => {
if (this.currentEnumeratorAsync) {
// overruled case 1: after we started the async, we
// notice that there is an outstanding tab completion
// request; here we try cancelling it, in the hopes
// that it hasn't already started its remote fetch;
// this is request2 overruling request1
clearTimeout(this.currentEnumeratorAsync)
}
const myEnumeratorAsync = global.setTimeout(async () => {
const completions = await findCompletionsFromRegistrar(input.props.tab || getCurrentTab(), commandLine, spec)
if (myEnumeratorAsync !== this.currentEnumeratorAsync) {
// overruled case 2: while waiting to fetch the
// completions, a second tab completion request was
// initiated; this is request1 overruling itself,
// after noticing that a (later) request2 is also in
// flight --- the rest of this method is
// synchronous, so this should be the last necessary
// race check
return
}
if (completions && completions.length > 0) {
// this.presentEnumeratorSuggestions(lastIdx, last, completions)
this.currentEnumeratorAsync = undefined
}
resolve({ partial: last, completions })
}, 0)
this.currentEnumeratorAsync = myEnumeratorAsync
})
} else {
return undefined
}
}
/** User has typed another key, while a tab completion is active */
public key(event: KeyboardEvent) {
const key = event.key
if (key === 'Escape' || key === 'Control' || key === 'Meta') {
this.done()
} else {
if (
key === 'Tab' &&
this.input.state.prompt &&
this.input.state.prompt.value.length > 0 &&
!this.input.state.tabCompletion
) {
// Swallow any Tab keys if we are currently presenting a set
// of completions. This is so we can redirect those keys
// instead to tab through the completions
event.stopPropagation()
event.preventDefault()
}
// async to make sure prompt updates occur
setTimeout(() => this.again(key === 'Tab'))
}
}
/** Perform a state update to reflect the new set of Completions. */
protected update(spec: Completions, prefillPartialMatches: boolean) {
const { completions } = spec
if (!completions || completions.length === 0 || (!prefillPartialMatches && !spec.partial)) {
// if either (no completions) or (completions, but no partial matches)
this.done()
} else if (completions.length === 1 && prefillPartialMatches) {
new TabCompletionStateWithSingleSuggestion(this.input, completions[0], spec.shellEscapeNotNeeded).render()
this.done()
} else {
this.input.setState({
tabCompletion: new TabCompletionStateWithMultipleSuggestions(this.input, spec, prefillPartialMatches)
})
}
}
/** Is the new set of Completions worth a re-render? */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected willUpdate(completions: Completions, prefillPartialMatches: boolean): boolean {
return !!completions
}
/**
* Respond to additional input.
*
* @param prefillPartialMatches Update the prompt with partial matches?
*/
private async again(prefillPartialMatches: boolean) {
const completions = await this.findCompletions()
if (this.willUpdate(completions, prefillPartialMatches)) {
// avoid flicker; we are using a PureComponent, so need to manage this ourselves
this.update(completions, prefillPartialMatches)
}
}
/** Terminate this tab completion */
public done() {
this.input.setState({ tabCompletion: undefined })
}
public abstract render(): false | React.ReactElement
}
/**
* TabCompletion initial state, before we have enumerated the possibilities.
*
*/
class TabCompletionInitialState extends TabCompletionState {
public constructor(input: Input) {
super(input)
this.init()
}
private async init() {
const completions = await this.findCompletions()
if (this.willUpdate(completions, true)) {
this.update(completions, true)
}
}
public render() {
return false as const
}
}
/**
* Update the prompt value. Note that `prompt.value = newValue` will
* not trigger onChange events, so a bit of round-about is needed.
*
*/
function setPromptValue(prompt: InputElement, newValue: string, selectionStart: number) {
const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set
nativeInputValueSetter.call(prompt, newValue)
prompt.selectionStart = selectionStart
prompt.selectionEnd = selectionStart
setTimeout(() => prompt.dispatchEvent(new Event('change', { bubbles: true })))
}
/**
* TabCompletion in a state where we have exactly one completion to offer the user.
*
*/
class TabCompletionStateWithSingleSuggestion extends TabCompletionState {
public constructor(
input: Input,
private readonly completion: CompletionResponse,
private readonly shellEscapeNotNeeded: boolean
) {
super(input)
}
public render() {
const lastIdx = this.lastIdx
const prompt = this.input.state.prompt
const prefix = prompt.value.slice(0, lastIdx)
const suffix = prompt.value.slice(lastIdx)
const extra =
typeof this.completion === 'string'
? shellescapeIfNeeded(this.completion, prefix, this.shellEscapeNotNeeded)
: shellescapeIfNeeded(this.completion.completion, prefix, this.shellEscapeNotNeeded) +
(this.completion.addSpace ? ' ' : '')
const newValue = prefix + extra + suffix
const selectionStart = lastIdx + extra.length
setPromptValue(prompt, newValue, selectionStart)
prompt.focus()
// nothing to render in the tab completion portion of the UI.
return false as const
}
}
/**
* TabCompletion in a state where we have more than one completion to offer the user.
*
*/
class TabCompletionStateWithMultipleSuggestions extends TabCompletionState {
private readonly completions: Completions
public constructor(input: Input, completions: Completions, private readonly prefillPartialMatches: boolean) {
super(input)
const longestPrefix = TabCompletionStateWithMultipleSuggestions.findLongestPrefixMatch(completions)
if (longestPrefix && prefillPartialMatches) {
// update the prompt directly; is this dangerous? to sidestep react?
const prompt = this.input.state.prompt
const lastIdx = this.lastIdx
const prefix = prompt.value.slice(0, lastIdx)
const suffix = prompt.value.slice(lastIdx)
const extra = shellescape(longestPrefix)
const newValue = prefix + extra + suffix
const selectionStart = lastIdx + extra.length
setPromptValue(prompt, newValue, selectionStart)
const prefixed = completions.completions.map(_ => {
if (typeof _ === 'string') {
return _.slice(longestPrefix.length)
} else {
return Object.assign({}, _, {
completion: _.completion.slice(longestPrefix.length)
})
}
})
// add longestPrefix to partial, and strip longestPrefix off the completions
this.completions = { partial: completions.partial + longestPrefix, completions: prefixed }
} else {
this.completions = completions
}
}
/** User has selected one of the N completions. Transition to a SingleSuggestion state. */
private completeWith(idx: number) {
this.input.setState({
tabCompletion: new TabCompletionStateWithSingleSuggestion(
this.input,
this.completions.completions[idx],
this.completions.shellEscapeNotNeeded
)
})
}
private renderOneCompletion(completion: CompletionResponse, idx: number) {
let value: string
let preText: string
let postText: string
if (typeof completion === 'string') {
value = this.completions.partial + completion
preText = this.completions.partial
postText = completion
} else {
if (completion.label) {
value = completion.label
preText = completion.label.replace(completion.completion, '')
postText = completion.completion
} else {
value = this.completions.partial + completion.completion
preText = this.completions.partial
postText = completion.completion
}
}
return (
<div className="kui--tab-completions--option" key={idx} data-value={value}>
<Button isSmall tabIndex={1} onClick={() => this.completeWith(idx)}>
<React.Fragment>
<span className="kui--tab-completions--option-partial">{preText}</span>
<span className="kui--tab-completions--option-completion">{postText}</span>
</React.Fragment>
</Button>
</div>
)
}
/** Helper for `willUpdate` */
private eq(c1: CompletionResponse, c2: CompletionResponse): boolean {
return (
(typeof c1 === 'string' && typeof c2 === 'string' && c1 === c2) ||
(typeof c1 !== 'string' && typeof c2 !== 'string' && c1.completion === c2.completion)
)
}
/** Since we use a React.PureComponent, we will need to manage the `willUpdate` lifecycle. */
protected willUpdate(completions: Completions, prefillPartialMatches: boolean): boolean {
return (
this.prefillPartialMatches !== prefillPartialMatches ||
(!!this.completions.completions && !completions.completions) ||
(!this.completions.completions && !!completions.completions) ||
this.completions.completions.length !== completions.completions.length ||
!(
this.completions.completions.length === completions.completions.length &&
this.completions.completions.every((_, idx) => this.eq(_, completions.completions[idx]))
)
)
}
/**
* Maybe this just reflects our lack of appreciation for css
* grid-layout... but for now, we hack it to estimate the width of
* the columns in the grid-layout we generate.
*
*/
private estimateGridColumnWidth() {
const longest = this.completions.completions
.map(completion =>
typeof completion === 'string'
? this.completions.partial + completion
: completion.label || this.completions.partial + completion.completion
)
.reduce(
(soFar, str) => {
if (str.length > soFar.max) {
return { max: str.length, str }
} else {
return soFar
}
},
{ max: 0, str: '' }
)
// add some em-sized spaces for good measure
let ex = 0
let em = 2 // <-- for good measure
for (let idx = 0; idx < longest.str.length; idx++) {
const char = longest.str.charAt(idx)
if (char === 'm') em++
else ex++
}
return { ex, em }
}
/** User has typed xxxx, and we have completions xxxx1 and xxxx2. Update state to reflect the xxxx partial completion */
private static findLongestPrefixMatch(ccc: Completions) {
const completions = ccc.completions.map(_ => (typeof _ === 'string' ? _ : _.completion))
const shortest = completions.reduce(
(minLength: false | number, completion) =>
!minLength ? completion.length : Math.min(minLength, completion.length),
false
)
if (shortest !== false) {
for (let idx = 0; idx < shortest; idx++) {
const char = completions[0].charAt(idx)
for (let jdx = 1; jdx < completions.length; jdx++) {
const other = completions[jdx].charAt(idx)
if (char !== other) {
if (idx > 0) {
// then we found some common prefix
return completions[0].slice(0, idx)
} else {
return
}
}
}
}
}
}
/** Generate content to fill in the tab completion part of the Input component */
public render() {
const { ex, em } = this.estimateGridColumnWidth()
// we're adding content to the bottom of the Terminal; make sure it's visible
setTimeout(() => this.input.state.prompt.scrollIntoView(), 5)
return (
<div
className="kui--tab-completions grid-layout"
style={{ gridTemplateColumns: `repeat(auto-fill, minmax(calc(${ex}ex + ${em}em), auto))` }}
>
{this.completions.completions.map((_, idx) => this.renderOneCompletion(_, idx))}
</div>
)
}
}
/**
* User has hit Tab in an Input component. Should we initialize a tab completion state?
*
*/
export default function startTabCompletion(input: Input, evt: KeyboardEvent) {
if (input.state.prompt && input.state.prompt.value.length === 0) {
debug('ignoring tab completion for empty prompt') // <-- no, the Input prompt is empty
return
} else {
debug('capturing tab event for tab completion')
evt.preventDefault()
}
input.setState({ tabCompletion: new TabCompletionInitialState(input) }) // <-- yes, initialize!
}