-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathsearch-in-workspace-widget.tsx
588 lines (523 loc) · 24.1 KB
/
search-in-workspace-widget.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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
/********************************************************************************
* Copyright (C) 2018 TypeFox and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the Eclipse
* Public License v. 2.0 are satisfied: GNU General Public License, version 2
* with the GNU Classpath Exception which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
********************************************************************************/
import { Widget, Message, BaseWidget, Key, StatefulWidget, MessageLoop } from '@theia/core/lib/browser';
import { inject, injectable, postConstruct } from 'inversify';
import { SearchInWorkspaceResultTreeWidget } from './search-in-workspace-result-tree-widget';
import { SearchInWorkspaceOptions } from '../common/search-in-workspace-interface';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Event, Emitter, Disposable } from '@theia/core/lib/common';
import { WorkspaceService } from '@theia/workspace/lib/browser';
import { SearchInWorkspaceContextKeyService } from './search-in-workspace-context-key-service';
import { CancellationTokenSource } from '@theia/core';
import { ProgressBarFactory } from '@theia/core/lib/browser/progress-bar-factory';
import { EditorManager } from '@theia/editor/lib/browser';
import { SearchInWorkspacePreferences } from './search-in-workspace-preferences';
export interface SearchFieldState {
className: string;
enabled: boolean;
title: string;
}
@injectable()
export class SearchInWorkspaceWidget extends BaseWidget implements StatefulWidget {
static ID = 'search-in-workspace';
static LABEL = 'Search';
protected matchCaseState: SearchFieldState;
protected wholeWordState: SearchFieldState;
protected regExpState: SearchFieldState;
protected includeIgnoredState: SearchFieldState;
protected showSearchDetails = false;
protected _hasResults = false;
protected get hasResults(): boolean {
return this._hasResults;
}
protected set hasResults(hasResults: boolean) {
this.contextKeyService.hasSearchResult.set(hasResults);
this._hasResults = hasResults;
}
protected resultNumber = 0;
protected searchFieldContainerIsFocused = false;
protected searchInWorkspaceOptions: SearchInWorkspaceOptions;
protected searchTerm = '';
protected replaceTerm = '';
protected _showReplaceField = false;
protected get showReplaceField(): boolean {
return this._showReplaceField;
}
protected set showReplaceField(showReplaceField: boolean) {
this.contextKeyService.replaceActive.set(showReplaceField);
this._showReplaceField = showReplaceField;
}
protected contentNode: HTMLElement;
protected searchFormContainer: HTMLElement;
protected resultContainer: HTMLElement;
protected readonly onDidUpdateEmitter = new Emitter<void>();
readonly onDidUpdate: Event<void> = this.onDidUpdateEmitter.event;
@inject(SearchInWorkspaceResultTreeWidget) protected readonly resultTreeWidget: SearchInWorkspaceResultTreeWidget;
@inject(WorkspaceService) protected readonly workspaceService: WorkspaceService;
@inject(SearchInWorkspaceContextKeyService)
protected readonly contextKeyService: SearchInWorkspaceContextKeyService;
@inject(ProgressBarFactory)
protected readonly progressBarFactory: ProgressBarFactory;
@inject(EditorManager) protected readonly editorManager: EditorManager;
@inject(SearchInWorkspacePreferences)
protected readonly searchInWorkspacePreferences: SearchInWorkspacePreferences;
@postConstruct()
protected init(): void {
this.id = SearchInWorkspaceWidget.ID;
this.title.label = SearchInWorkspaceWidget.LABEL;
this.title.caption = SearchInWorkspaceWidget.LABEL;
this.title.iconClass = 'search-in-workspace-tab-icon';
this.title.closable = true;
this.contentNode = document.createElement('div');
this.contentNode.classList.add('t-siw-search-container');
this.searchFormContainer = document.createElement('div');
this.searchFormContainer.classList.add('searchHeader');
this.contentNode.appendChild(this.searchFormContainer);
this.node.appendChild(this.contentNode);
this.matchCaseState = {
className: 'match-case',
enabled: false,
title: 'Match Case'
};
this.wholeWordState = {
className: 'whole-word',
enabled: false,
title: 'Match Whole Word'
};
this.regExpState = {
className: 'use-regexp',
enabled: false,
title: 'Use Regular Expression'
};
this.includeIgnoredState = {
className: 'include-ignored fa fa-eye',
enabled: false,
title: 'Include Ignored Files'
};
this.searchInWorkspaceOptions = {
matchCase: false,
matchWholeWord: false,
useRegExp: false,
includeIgnored: false,
include: [],
exclude: [],
maxResults: 2000
};
this.toDispose.push(this.resultTreeWidget.onChange(r => {
this.hasResults = r.size > 0;
this.resultNumber = 0;
const results = Array.from(r.values());
results.forEach(rootFolder =>
rootFolder.children.forEach(file => this.resultNumber += file.children.length)
);
this.update();
}));
this.toDispose.push(this.resultTreeWidget.onFocusInput(b => {
this.focusInputField();
}));
this.toDispose.push(this.resultTreeWidget);
this.toDispose.push(this.progressBarFactory({ container: this.node, insertMode: 'prepend', locationId: 'search' }));
}
storeState(): object {
return {
matchCaseState: this.matchCaseState,
wholeWordState: this.wholeWordState,
regExpState: this.regExpState,
includeIgnoredState: this.includeIgnoredState,
showSearchDetails: this.showSearchDetails,
searchInWorkspaceOptions: this.searchInWorkspaceOptions,
searchTerm: this.searchTerm,
replaceTerm: this.replaceTerm,
showReplaceField: this.showReplaceField
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
restoreState(oldState: any): void {
this.matchCaseState = oldState.matchCaseState;
this.wholeWordState = oldState.wholeWordState;
this.regExpState = oldState.regExpState;
this.includeIgnoredState = oldState.includeIgnoredState;
this.showSearchDetails = oldState.showSearchDetails;
this.searchInWorkspaceOptions = oldState.searchInWorkspaceOptions;
this.searchTerm = oldState.searchTerm;
this.replaceTerm = oldState.replaceTerm;
this.showReplaceField = oldState.showReplaceField;
this.resultTreeWidget.replaceTerm = this.replaceTerm;
this.resultTreeWidget.showReplaceButtons = this.showReplaceField;
this.refresh();
}
findInFolder(uris: string[]): void {
this.showSearchDetails = true;
const values = Array.from(new Set(uris.map(uri => `${uri}/**`)));
const value = values.join(', ');
this.searchInWorkspaceOptions.include = values;
const include = document.getElementById('include-glob-field');
if (include) {
(include as HTMLInputElement).value = value;
}
this.update();
}
/**
* Update the search term and input field.
* @param term the search term.
*/
updateSearchTerm(term: string): void {
this.searchTerm = term;
const search = document.getElementById('search-input-field');
if (search) {
(search as HTMLInputElement).value = term;
}
this.refresh();
}
hasResultList(): boolean {
return this.hasResults;
}
hasSearchTerm(): boolean {
return this.searchTerm !== '';
}
refresh(): void {
this.resultTreeWidget.search(this.searchTerm, this.searchInWorkspaceOptions);
this.update();
}
getCancelIndicator(): CancellationTokenSource | undefined {
return this.resultTreeWidget.cancelIndicator;
}
collapseAll(): void {
this.resultTreeWidget.collapseAll();
this.update();
}
clear(): void {
this.searchTerm = '';
this.replaceTerm = '';
this.searchInWorkspaceOptions.include = [];
this.searchInWorkspaceOptions.exclude = [];
this.includeIgnoredState.enabled = false;
this.matchCaseState.enabled = false;
this.wholeWordState.enabled = false;
this.regExpState.enabled = false;
const search = document.getElementById('search-input-field');
const replace = document.getElementById('replace-input-field');
const include = document.getElementById('include-glob-field');
const exclude = document.getElementById('exclude-glob-field');
if (search && replace && include && exclude) {
(search as HTMLInputElement).value = '';
(replace as HTMLInputElement).value = '';
(include as HTMLInputElement).value = '';
(exclude as HTMLInputElement).value = '';
}
this.resultTreeWidget.search(this.searchTerm, this.searchInWorkspaceOptions);
this.update();
}
protected onAfterAttach(msg: Message): void {
super.onAfterAttach(msg);
ReactDOM.render(<React.Fragment>{this.renderSearchHeader()}{this.renderSearchInfo()}</React.Fragment>, this.searchFormContainer);
Widget.attach(this.resultTreeWidget, this.contentNode);
this.toDisposeOnDetach.push(Disposable.create(() => {
Widget.detach(this.resultTreeWidget);
}));
}
protected onUpdateRequest(msg: Message): void {
super.onUpdateRequest(msg);
const searchInfo = this.renderSearchInfo();
if (searchInfo) {
ReactDOM.render(<React.Fragment>{this.renderSearchHeader()}{searchInfo}</React.Fragment>, this.searchFormContainer);
this.onDidUpdateEmitter.fire(undefined);
}
}
protected onResize(msg: Widget.ResizeMessage): void {
super.onResize(msg);
MessageLoop.sendMessage(this.resultTreeWidget, Widget.ResizeMessage.UnknownSize);
}
protected onAfterShow(msg: Message): void {
super.onAfterShow(msg);
this.focusInputField();
this.contextKeyService.searchViewletVisible.set(true);
}
protected onAfterHide(msg: Message): void {
super.onAfterHide(msg);
this.contextKeyService.searchViewletVisible.set(false);
}
protected onActivateRequest(msg: Message): void {
super.onActivateRequest(msg);
this.focusInputField();
}
protected focusInputField(): void {
const f = document.getElementById('search-input-field');
if (f) {
(f as HTMLInputElement).focus();
(f as HTMLInputElement).select();
}
}
protected renderSearchHeader(): React.ReactNode {
const searchAndReplaceContainer = this.renderSearchAndReplace();
const searchDetails = this.renderSearchDetails();
return <div>{searchAndReplaceContainer}{searchDetails}</div>;
}
protected renderSearchAndReplace(): React.ReactNode {
const toggleContainer = this.renderReplaceFieldToggle();
const searchField = this.renderSearchField();
const replaceField = this.renderReplaceField();
return <div className='search-and-replace-container'>
{toggleContainer}
<div className='search-and-replace-fields'>
{searchField}
{replaceField}
</div>
</div>;
}
protected renderReplaceFieldToggle(): React.ReactNode {
const toggle = <span className={`fa fa-caret-${this.showReplaceField ? 'down' : 'right'}`}></span>;
return <div
title='Toggle Replace'
className='replace-toggle'
tabIndex={0}
onClick={e => {
const elArr = document.getElementsByClassName('replace-toggle');
if (elArr && elArr.length > 0) {
(elArr[0] as HTMLElement).focus();
}
this.showReplaceField = !this.showReplaceField;
this.resultTreeWidget.showReplaceButtons = this.showReplaceField;
this.update();
}}>
{toggle}
</div>;
}
protected renderNotification(): React.ReactNode {
if (this.workspaceService.tryGetRoots().length <= 0 && this.editorManager.all.length <= 0) {
return <div className='search-notification show'>
<div>You have not opened or specified a folder. Only open files are currently searched.</div>
</div>;
}
return <div
className={`search-notification ${this.searchInWorkspaceOptions.maxResults && this.resultNumber >= this.searchInWorkspaceOptions.maxResults ? 'show' : ''}`}>
<div>
This is only a subset of all results. Use a more specific search term to narrow down the result list.
</div>
</div>;
}
protected readonly focusSearchFieldContainer = () => this.doFocusSearchFieldContainer();
protected doFocusSearchFieldContainer(): void {
this.searchFieldContainerIsFocused = true;
this.update();
}
protected readonly unfocusSearchFieldContainer = () => this.doUnfocusSearchFieldContainer();
protected doUnfocusSearchFieldContainer(): void {
this.searchFieldContainerIsFocused = false;
this.update();
}
protected readonly search = (e: React.KeyboardEvent) => {
e.persist();
const searchOnType = this.searchInWorkspacePreferences['search.searchOnType'];
if (searchOnType) {
const delay = searchOnType ? this.searchInWorkspacePreferences['search.searchOnTypeDebouncePeriod'] : 0;
setTimeout(() => this.doSearch(e), delay);
}
};
protected readonly onKeyDownSearch = (e: React.KeyboardEvent) => {
if (e.keyCode === Key.ENTER.keyCode) {
this.searchTerm = (e.target as HTMLInputElement).value;
this.resultTreeWidget.search(this.searchTerm, (this.searchInWorkspaceOptions || {}));
}
};
protected doSearch(e: React.KeyboardEvent): void {
if (e.target) {
const searchValue = (e.target as HTMLInputElement).value;
if (Key.ARROW_DOWN.keyCode === e.keyCode) {
this.resultTreeWidget.focusFirstResult();
} else if (this.searchTerm === searchValue && Key.ENTER.keyCode !== e.keyCode) {
return;
} else {
this.searchTerm = searchValue;
this.resultTreeWidget.search(this.searchTerm, (this.searchInWorkspaceOptions || {}));
}
}
}
protected renderSearchField(): React.ReactNode {
const input = <input
id='search-input-field'
className='theia-input'
title='Search'
type='text'
size={1}
placeholder='Search'
defaultValue={this.searchTerm}
autoComplete='off'
onKeyUp={this.search}
onKeyDown={this.onKeyDownSearch}
onFocus={this.handleFocusSearchInputBox}
onBlur={this.handleBlurSearchInputBox}
></input>;
const notification = this.renderNotification();
const optionContainer = this.renderOptionContainer();
const tooMany = this.searchInWorkspaceOptions.maxResults && this.resultNumber >= this.searchInWorkspaceOptions.maxResults ? 'tooManyResults' : '';
const className = `search-field-container ${tooMany} ${this.searchFieldContainerIsFocused ? 'focused' : ''}`;
return <div className={className}>
<div className='search-field' tabIndex={-1} onFocus={this.focusSearchFieldContainer} onBlur={this.unfocusSearchFieldContainer}>
{input}
{optionContainer}
</div>
{notification}
</div>;
}
protected handleFocusSearchInputBox = () => this.contextKeyService.setSearchInputBoxFocus(true);
protected handleBlurSearchInputBox = () => this.contextKeyService.setSearchInputBoxFocus(false);
protected readonly updateReplaceTerm = (e: React.KeyboardEvent) => this.doUpdateReplaceTerm(e);
protected doUpdateReplaceTerm(e: React.KeyboardEvent): void {
if (e.target) {
this.replaceTerm = (e.target as HTMLInputElement).value;
this.resultTreeWidget.replaceTerm = this.replaceTerm;
this.resultTreeWidget.search(this.searchTerm, (this.searchInWorkspaceOptions || {}));
this.update();
}
}
protected renderReplaceField(): React.ReactNode {
const replaceAllButtonContainer = this.renderReplaceAllButtonContainer();
return <div className={`replace-field${this.showReplaceField ? '' : ' hidden'}`}>
<input
id='replace-input-field'
className='theia-input'
title='Replace'
type='text'
size={1}
placeholder='Replace'
defaultValue={this.replaceTerm}
onKeyUp={this.updateReplaceTerm}
onFocus={this.handleFocusReplaceInputBox}
onBlur={this.handleBlurReplaceInputBox}>
</input>
{replaceAllButtonContainer}
</div>;
}
protected handleFocusReplaceInputBox = () => this.contextKeyService.setReplaceInputBoxFocus(true);
protected handleBlurReplaceInputBox = () => this.contextKeyService.setReplaceInputBoxFocus(false);
protected renderReplaceAllButtonContainer(): React.ReactNode {
// The `Replace All` button is enabled if there is a search term present with results.
const enabled: boolean = this.searchTerm !== '' && this.resultNumber > 0;
return <div className='replace-all-button-container'>
<span
title='Replace All'
className={`replace-all-button${enabled ? ' ' : ' disabled'}`}
onClick={() => {
if (enabled) {
this.resultTreeWidget.replace(undefined);
}
}}>
</span>
</div>;
}
protected renderOptionContainer(): React.ReactNode {
const matchCaseOption = this.renderOptionElement(this.matchCaseState);
const wholeWordOption = this.renderOptionElement(this.wholeWordState);
const regexOption = this.renderOptionElement(this.regExpState);
const includeIgnoredOption = this.renderOptionElement(this.includeIgnoredState);
return <div className='option-buttons'>{matchCaseOption}{wholeWordOption}{regexOption}{includeIgnoredOption}</div>;
}
protected renderOptionElement(opt: SearchFieldState): React.ReactNode {
return <span
className={`${opt.className} option ${opt.enabled ? 'enabled' : ''}`}
title={opt.title}
onClick={() => this.handleOptionClick(opt)}></span>;
}
protected handleOptionClick(option: SearchFieldState): void {
option.enabled = !option.enabled;
this.updateSearchOptions();
this.searchFieldContainerIsFocused = true;
this.resultTreeWidget.search(this.searchTerm, this.searchInWorkspaceOptions);
this.update();
}
protected updateSearchOptions(): void {
this.searchInWorkspaceOptions.matchCase = this.matchCaseState.enabled;
this.searchInWorkspaceOptions.matchWholeWord = this.wholeWordState.enabled;
this.searchInWorkspaceOptions.useRegExp = this.regExpState.enabled;
this.searchInWorkspaceOptions.includeIgnored = this.includeIgnoredState.enabled;
}
protected renderSearchDetails(): React.ReactNode {
const expandButton = this.renderExpandGlobFieldsButton();
const globFieldContainer = this.renderGlobFieldContainer();
return <div className='search-details'>{expandButton}{globFieldContainer}</div>;
}
protected renderGlobFieldContainer(): React.ReactNode {
const includeField = this.renderGlobField('include');
const excludeField = this.renderGlobField('exclude');
return <div className={`glob-field-container${!this.showSearchDetails ? ' hidden' : ''}`}>{includeField}{excludeField}</div>;
}
protected renderExpandGlobFieldsButton(): React.ReactNode {
return <div className='button-container'>
<span
title='Toggle Search Details'
className='fa fa-ellipsis-h btn'
onClick={() => {
this.showSearchDetails = !this.showSearchDetails;
this.update();
}}></span>
</div>;
}
protected renderGlobField(kind: 'include' | 'exclude'): React.ReactNode {
const currentValue = this.searchInWorkspaceOptions[kind];
const value = currentValue && currentValue.join(', ') || '';
return <div className='glob-field'>
<div className='label'>{'files to ' + kind}</div>
<input
className='theia-input'
type='text'
size={1}
defaultValue={value}
id={kind + '-glob-field'}
onKeyUp={e => {
if (e.target) {
if (Key.ENTER.keyCode === e.keyCode) {
this.resultTreeWidget.search(this.searchTerm, this.searchInWorkspaceOptions);
} else {
this.searchInWorkspaceOptions[kind] = this.splitOnComma((e.target as HTMLInputElement).value);
}
}
}}
onFocus={kind === 'include' ? this.handleFocusIncludesInputBox : this.handleFocusExcludesInputBox}
onBlur={kind === 'include' ? this.handleBlurIncludesInputBox : this.handleBlurExcludesInputBox}></input>
</div>;
}
protected handleFocusIncludesInputBox = () => this.contextKeyService.setPatternExcludesInputBoxFocus(true);
protected handleBlurIncludesInputBox = () => this.contextKeyService.setPatternExcludesInputBoxFocus(false);
protected handleFocusExcludesInputBox = () => this.contextKeyService.setPatternExcludesInputBoxFocus(true);
protected handleBlurExcludesInputBox = () => this.contextKeyService.setPatternExcludesInputBoxFocus(false);
protected splitOnComma(patterns: string): string[] {
return patterns.length > 0 ? patterns.split(',').map(s => s.trim()) : [];
}
protected renderSearchInfo(): React.ReactNode {
let message = '';
if (this.searchTerm) {
if (this.searchInWorkspaceOptions.include && this.searchInWorkspaceOptions.include.length > 0 && this.resultNumber === 0) {
message = `No results found in '${this.searchInWorkspaceOptions.include}'`;
} else if (this.resultNumber === 0) {
message = 'No results found.';
} else {
if (this.resultNumber === 1 && this.resultTreeWidget.fileNumber === 1) {
message = `${this.resultNumber} result in ${this.resultTreeWidget.fileNumber} file`;
} else if (this.resultTreeWidget.fileNumber === 1) {
message = `${this.resultNumber} results in ${this.resultTreeWidget.fileNumber} file`;
} else if (this.resultTreeWidget.fileNumber > 0) {
message = `${this.resultNumber} results in ${this.resultTreeWidget.fileNumber} files`;
} else {
// if fileNumber === 0, return undefined so that `onUpdateRequest()` would not re-render component
return undefined;
}
}
}
return <div className='search-info'>{message}</div>;
}
}