-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathsearch-in-workspace-widget.tsx
716 lines (638 loc) · 30.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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
/********************************************************************************
* 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, KeyCode, codicon } from '@theia/core/lib/browser';
import { inject, injectable, postConstruct } from '@theia/core/shared/inversify';
import { SearchInWorkspaceResultTreeWidget } from './search-in-workspace-result-tree-widget';
import { SearchInWorkspaceOptions } from '../common/search-in-workspace-interface';
import * as React from '@theia/core/shared/react';
import * as ReactDOM from '@theia/core/shared/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';
import { SearchInWorkspaceInput } from './components/search-in-workspace-input';
import { nls } from '@theia/core/lib/common/nls';
export interface SearchFieldState {
className: string;
enabled: boolean;
title: string;
}
@injectable()
export class SearchInWorkspaceWidget extends BaseWidget implements StatefulWidget {
static ID = 'search-in-workspace';
static LABEL = nls.localizeByDefault('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 = '';
private searchRef = React.createRef<SearchInWorkspaceInput>();
private replaceRef = React.createRef<SearchInWorkspaceInput>();
private includeRef = React.createRef<SearchInWorkspaceInput>();
private excludeRef = React.createRef<SearchInWorkspaceInput>();
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 = codicon('search');
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.tabIndex = 0;
this.node.appendChild(this.contentNode);
this.matchCaseState = {
className: codicon('case-sensitive'),
enabled: false,
title: nls.localizeByDefault('Match Case')
};
this.wholeWordState = {
className: codicon('whole-word'),
enabled: false,
title: nls.localizeByDefault('Match Whole Word')
};
this.regExpState = {
className: codicon('regex'),
enabled: false,
title: nls.localizeByDefault('Use Regular Expression')
};
this.includeIgnoredState = {
className: codicon('eye'),
enabled: false,
title: nls.localize('theia/search-in-workspace/includeIgnoredFiles', '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.searchInWorkspacePreferences.onPreferenceChanged(e => {
if (e.preferenceName === 'search.smartCase') {
this.performSearch();
}
}));
this.toDispose.push(this.resultTreeWidget);
this.toDispose.push(this.resultTreeWidget.onExpansionChanged(() => {
this.onDidUpdateEmitter.fire();
}));
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,
searchHistoryState: this.searchRef.current?.state,
replaceHistoryState: this.replaceRef.current?.state,
includeHistoryState: this.includeRef.current?.state,
excludeHistoryState: this.excludeRef.current?.state,
};
}
// 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;
// Override the title of the restored state, as we could have changed languages in between
this.matchCaseState.title = nls.localizeByDefault('Match Case');
this.wholeWordState.title = nls.localizeByDefault('Match Whole Word');
this.regExpState.title = nls.localizeByDefault('Use Regular Expression');
this.includeIgnoredState.title = nls.localize('theia/search-in-workspace/includeIgnoredFiles', 'Include Ignored Files');
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.searchRef.current?.setState(oldState.searchHistoryState);
this.replaceRef.current?.setState(oldState.replaceHistoryState);
this.includeRef.current?.setState(oldState.includeHistoryState);
this.excludeRef.current?.setState(oldState.excludeHistoryState);
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.
* @param showReplaceField controls if the replace field should be displayed.
*/
updateSearchTerm(term: string, showReplaceField?: boolean): void {
this.searchTerm = term;
const search = document.getElementById('search-input-field');
if (search) {
(search as HTMLInputElement).value = term;
}
if (showReplaceField) {
this.showReplaceField = true;
}
this.refresh();
}
hasResultList(): boolean {
return this.hasResults;
}
hasSearchTerm(): boolean {
return this.searchTerm !== '';
}
refresh(): void {
this.performSearch();
this.update();
}
getCancelIndicator(): CancellationTokenSource | undefined {
return this.resultTreeWidget.cancelIndicator;
}
collapseAll(): void {
this.resultTreeWidget.collapseAll();
this.update();
}
expandAll(): void {
this.resultTreeWidget.expandAll();
this.update();
}
areResultsCollapsed(): boolean {
return this.resultTreeWidget.areResultsCollapsed();
}
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.performSearch();
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={codicon(this.showReplaceField ? 'chevron-down' : 'chevron-right')}></span>;
return <div
title={nls.localizeByDefault('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>{nls.localize('theia/search-in-workspace/noFolderSpecified', '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>{nls.localize('theia/search-in-workspace/resultSubset',
'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 blurSearchFieldContainer = () => this.doBlurSearchFieldContainer();
protected doBlurSearchFieldContainer(): void {
this.searchFieldContainerIsFocused = false;
this.update();
}
/**
* @deprecated use `blurSearchFieldContainer` instead.
*/
protected readonly unfocusSearchFieldContainer = this.blurSearchFieldContainer;
/**
* @deprecated use `doBlurSearchFieldContainer` instead.
*/
protected doUnfocusSearchFieldContainer(): void {
this.doBlurSearchFieldContainer();
}
private _searchTimeout: number;
protected readonly search = (e: React.KeyboardEvent) => {
e.persist();
const searchOnType = this.searchInWorkspacePreferences['search.searchOnType'];
if (searchOnType) {
const delay = this.searchInWorkspacePreferences['search.searchOnTypeDebouncePeriod'] || 0;
window.clearTimeout(this._searchTimeout);
this._searchTimeout = window.setTimeout(() => this.doSearch(e), delay);
}
};
protected readonly onKeyDownSearch = (e: React.KeyboardEvent) => {
if (Key.ENTER.keyCode === KeyCode.createKeyCode(e.nativeEvent).key?.keyCode) {
this.searchTerm = (e.target as HTMLInputElement).value;
this.performSearch();
}
};
protected doSearch(e: React.KeyboardEvent): void {
if (e.target) {
const searchValue = (e.target as HTMLInputElement).value;
if (this.searchTerm === searchValue && Key.ENTER.keyCode !== KeyCode.createKeyCode(e.nativeEvent).key?.keyCode) {
return;
} else {
this.searchTerm = searchValue;
this.performSearch();
}
}
}
protected performSearch(): void {
const searchOptions: SearchInWorkspaceOptions = {
...this.searchInWorkspaceOptions,
followSymlinks: this.shouldFollowSymlinks(),
matchCase: this.shouldMatchCase()
};
this.resultTreeWidget.search(this.searchTerm, searchOptions);
}
protected shouldFollowSymlinks(): boolean {
return this.searchInWorkspacePreferences['search.followSymlinks'];
}
/**
* Determine if search should be case sensitive.
*/
protected shouldMatchCase(): boolean {
if (this.matchCaseState.enabled) {
return this.matchCaseState.enabled;
}
// search.smartCase makes siw search case-sensitive if the search term contains uppercase letter(s).
return (
!!this.searchInWorkspacePreferences['search.smartCase']
&& this.searchTerm !== this.searchTerm.toLowerCase()
);
}
protected renderSearchField(): React.ReactNode {
const input = <SearchInWorkspaceInput
id='search-input-field'
className='theia-input'
title={SearchInWorkspaceWidget.LABEL}
type='text'
size={1}
placeholder={SearchInWorkspaceWidget.LABEL}
defaultValue={this.searchTerm}
autoComplete='off'
onKeyUp={this.search}
onKeyDown={this.onKeyDownSearch}
onFocus={this.handleFocusSearchInputBox}
onBlur={this.handleBlurSearchInputBox}
ref={this.searchRef}
/>;
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.blurSearchFieldContainer}>
{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.performSearch();
this.update();
}
}
protected renderReplaceField(): React.ReactNode {
const replaceAllButtonContainer = this.renderReplaceAllButtonContainer();
const replace = nls.localizeByDefault('Replace');
return <div className={`replace-field${this.showReplaceField ? '' : ' hidden'}`}>
<SearchInWorkspaceInput
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}
ref={this.replaceRef}
/>
{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={nls.localizeByDefault('Replace All')}
className={`${codicon('replace-all', true)} ${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.performSearch();
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={nls.localizeByDefault('Toggle Search Details')}
className={codicon('ellipsis')}
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(', ') || '';
const labelKey = `vscode/searchView/searchScope.${kind}s`;
return <div className='glob-field'>
<div className='label'>{nls.localize(labelKey, 'files to ' + kind)}</div>
<SearchInWorkspaceInput
className='theia-input'
type='text'
size={1}
defaultValue={value}
id={kind + '-glob-field'}
onKeyUp={e => {
if (e.target) {
const targetValue = (e.target as HTMLInputElement).value || '';
let shouldSearch = Key.ENTER.keyCode === KeyCode.createKeyCode(e.nativeEvent).key?.keyCode;
const currentOptions = (this.searchInWorkspaceOptions[kind] || []).slice().map(s => s.trim()).sort();
const candidateOptions = this.splitOnComma(targetValue).map(s => s.trim()).sort();
const sameAs = (left: string[], right: string[]) => {
if (left.length !== right.length) {
return false;
}
for (let i = 0; i < left.length; i++) {
if (left[i] !== right[i]) {
return false;
}
}
return true;
};
if (!sameAs(currentOptions, candidateOptions)) {
this.searchInWorkspaceOptions[kind] = this.splitOnComma(targetValue);
shouldSearch = true;
}
if (shouldSearch) {
this.performSearch();
}
}
}}
onFocus={kind === 'include' ? this.handleFocusIncludesInputBox : this.handleFocusExcludesInputBox}
onBlur={kind === 'include' ? this.handleBlurIncludesInputBox : this.handleBlurExcludesInputBox}
ref={kind === 'include' ? this.includeRef : this.excludeRef}
/>
</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 {
const message = this.getSearchResultMessage() || '';
return <div className='search-info'>{message}</div>;
}
protected getSearchResultMessage(): string | undefined {
if (!this.searchTerm) {
return undefined;
}
if (this.resultNumber === 0) {
const isIncludesPresent = this.searchInWorkspaceOptions.include && this.searchInWorkspaceOptions.include.length > 0;
const isExcludesPresent = this.searchInWorkspaceOptions.exclude && this.searchInWorkspaceOptions.exclude.length > 0;
let message: string;
if (isIncludesPresent && isExcludesPresent) {
message = nls.localizeByDefault("No results found in '{0}' excluding '{1}' - ",
this.searchInWorkspaceOptions.include!.toString(), this.searchInWorkspaceOptions.exclude!.toString());
} else if (isIncludesPresent) {
message = nls.localizeByDefault("No results found in '{0}' - ",
this.searchInWorkspaceOptions.include!.toString());
} else if (isExcludesPresent) {
message = nls.localizeByDefault("No results found excluding '{0}' - ",
this.searchInWorkspaceOptions.exclude!.toString());
} else {
message = nls.localizeByDefault('No results found. - ');
}
// We have to trim here as vscode will always add a trailing " - " string
return message.substring(0, message.length - 2).trim();
} else {
if (this.resultNumber === 1 && this.resultTreeWidget.fileNumber === 1) {
return nls.localizeByDefault('{0} result in {1} file',
this.resultNumber.toString(), this.resultTreeWidget.fileNumber.toString());
} else if (this.resultTreeWidget.fileNumber === 1) {
return nls.localizeByDefault('{0} results in {1} file',
this.resultNumber.toString(), this.resultTreeWidget.fileNumber.toString());
} else if (this.resultTreeWidget.fileNumber > 0) {
return nls.localizeByDefault('{0} results in {1} files',
this.resultNumber.toString(), this.resultTreeWidget.fileNumber.toString());
} else {
// if fileNumber === 0, return undefined so that `onUpdateRequest()` would not re-render component
return undefined;
}
}
}
}