-
-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathindex.tsx
2343 lines (2053 loc) · 66.7 KB
/
index.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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {Component, createRef} from 'react';
import styled from '@emotion/styled';
import * as Sentry from '@sentry/react';
import debounce from 'lodash/debounce';
import isEqual from 'lodash/isEqual';
import {addErrorMessage} from 'sentry/actionCreators/indicator';
import {fetchRecentSearches, saveRecentSearch} from 'sentry/actionCreators/savedSearches';
import type {Client} from 'sentry/api';
import {Button} from 'sentry/components/core/button';
import {ButtonBar} from 'sentry/components/core/button/buttonBar';
import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
import type {
BooleanOperator,
ParseResult,
SearchConfig,
TermOperator,
TokenResult,
} from 'sentry/components/searchSyntax/parser';
import {
FilterType,
InvalidReason,
parseSearch,
Token,
} from 'sentry/components/searchSyntax/parser';
import HighlightQuery from 'sentry/components/searchSyntax/renderer';
import {
getKeyName,
isOperator,
isWithinToken,
treeResultLocator,
} from 'sentry/components/searchSyntax/utils';
import {
DEFAULT_DEBOUNCE_DURATION,
MAX_AUTOCOMPLETE_RELEASES,
NEGATION_OPERATOR,
} from 'sentry/constants';
import {IconClose, IconEllipsis, IconSearch} from 'sentry/icons';
import {t} from 'sentry/locale';
import MemberListStore from 'sentry/stores/memberListStore';
import {space} from 'sentry/styles/space';
import type {Tag, TagCollection} from 'sentry/types/group';
import {SavedSearchType} from 'sentry/types/group';
import type {WithRouterProps} from 'sentry/types/legacyReactRouter';
import type {Organization} from 'sentry/types/organization';
import type {User} from 'sentry/types/user';
import {defined} from 'sentry/utils';
import {trackAnalytics} from 'sentry/utils/analytics';
import type {FieldDefinition} from 'sentry/utils/fields';
import {FieldKind, FieldValueType, getFieldDefinition} from 'sentry/utils/fields';
import {MutableSearch} from 'sentry/utils/tokenizeSearch';
import withApi from 'sentry/utils/withApi';
import withOrganization from 'sentry/utils/withOrganization';
// eslint-disable-next-line no-restricted-imports
import withSentryRouter from 'sentry/utils/withSentryRouter';
import type {MenuItemProps} from '../dropdownMenu';
import {DropdownMenu} from '../dropdownMenu';
import SearchBarDatePicker from './searchBarDatePicker';
import SearchDropdown from './searchDropdown';
import SearchHotkeysListener from './searchHotkeysListener';
import type {AutocompleteGroup, SearchGroup, SearchItem, Shortcut} from './types';
import {ItemType, ShortcutType} from './types';
import {
addSpace,
createSearchGroups,
escapeTagValue,
filterKeysFromQuery,
generateOperatorEntryMap,
getAutoCompleteGroupForInvalidWildcard,
getDateTagAutocompleteGroups,
getSearchGroupWithItemMarkedActive,
getTagItemsFromKeys,
getValidOps,
removeSpace,
shortcuts,
} from './utils';
/**
* The max width in pixels of the search bar at which the buttons will
* have overflowed into the dropdown.
*/
const ACTION_OVERFLOW_WIDTH = 400;
/**
* Actions are moved to the overflow dropdown after each pixel step is reached.
*/
const ACTION_OVERFLOW_STEPS = 75;
const generateOpAutocompleteGroup = (
validOps: readonly TermOperator[],
tagName: string
): AutocompleteGroup => {
const operatorMap = generateOperatorEntryMap(tagName);
const operatorItems = validOps.map(op => operatorMap[op]);
return {
searchItems: operatorItems,
recentSearchItems: undefined,
tagName: '',
type: ItemType.TAG_OPERATOR,
};
};
function isMultiProject(projectIds: number[] | Readonly<number[] | undefined>) {
/**
* Returns true if projectIds is:
* - [] (My Projects)
* - [-1] (All Projects)
* - [a, b, ...] (two or more projects)
*/
if (projectIds === undefined) {
return false;
}
return (
projectIds.length === 0 ||
(projectIds.length === 1 && projectIds[0] === -1) ||
projectIds.length >= 2
);
}
function maybeFocusInput(input: HTMLTextAreaElement | null) {
// Cannot focus if there is no input or if the input is already focused
if (!input || document.activeElement === input) {
return;
}
input.focus();
}
const pickParserOptions = (props: Props) => {
const {
booleanKeys,
dateKeys,
durationKeys,
numericKeys,
percentageKeys,
sizeKeys,
textOperatorKeys,
getFilterWarning,
supportedTags,
highlightUnsupportedTags,
disallowedLogicalOperators,
disallowWildcard,
disallowFreeText,
disallowNegation,
invalidMessages,
} = props;
return {
booleanKeys,
dateKeys,
durationKeys,
numericKeys,
percentageKeys,
sizeKeys,
textOperatorKeys,
getFilterTokenWarning: getFilterWarning,
supportedTags,
validateKeys: highlightUnsupportedTags,
disallowedLogicalOperators,
disallowWildcard,
disallowFreeText,
disallowNegation,
invalidMessages,
} satisfies Partial<SearchConfig>;
};
export type ActionProps = {
api: Client;
/**
* The organization
*/
organization: Organization;
/**
* The current query
*/
query: string;
/**
* The saved search type passed to the search bar
*/
savedSearchType?: SavedSearchType;
};
export type ActionBarItem = {
/**
* Name of the action
*/
key: string;
makeAction: (props: ActionProps) => {
Button: React.ComponentType<any>;
menuItem: MenuItemProps;
};
};
type DefaultProps = {
defaultQuery: string;
/**
* Search items to display when there's no tag key. Is a tuple of search
* items and recent search items
*/
defaultSearchItems: [SearchItem[], SearchItem[]];
/**
* The lookup strategy for field definitions.
* Each SmartSearchBar instance can support a different list of fields and tags,
* their definitions may not overlap.
*/
fieldDefinitionGetter: (key: string) => FieldDefinition | null;
id: string;
includeLabel: boolean;
name: string;
/**
* Called when the user makes a search
*/
onSearch: (query: string) => void;
/**
* Input placeholder
*/
placeholder: string;
query: string | null;
/**
* If this is defined, attempt to save search term scoped to the user and
* the current org
*/
savedSearchType: SavedSearchType;
/**
* Map of tags
*/
supportedTags: TagCollection;
/**
* Wrap the input with a form. Useful if search bar is used within a parent
* form
*/
useFormWrapper: boolean;
/**
* Allows for customization of the invalid token messages.
*/
invalidMessages?: SearchConfig['invalidMessages'];
};
type Props = WithRouterProps &
Partial<DefaultProps> & {
api: Client;
organization: Organization;
/**
* Additional components to render as actions on the right of the search bar
*/
actionBarItems?: ActionBarItem[];
/**
* Keys that have boolean values
*/
booleanKeys?: Set<string>;
className?: string;
/**
* A function that provides the current search item and can return a custom invalid tag error message for the drop-down.
*/
customInvalidTagMessage?: (item: SearchItem) => React.ReactNode;
/**
* Keys that have date values
*/
dateKeys?: Set<string>;
/**
* The default search group to show when there is no query
*/
defaultSearchGroup?: SearchGroup;
/**
* Disabled control (e.g. read-only)
*/
disabled?: boolean;
/**
* Disables free text searches
*/
disallowFreeText?: boolean;
/**
* Disables negation searches
*/
disallowNegation?: boolean;
/**
* Disables wildcard searches (in freeText and in the value of key:value searches mode)
*/
disallowWildcard?: boolean;
/**
* Disables specified boolean operators
*/
disallowedLogicalOperators?: Set<BooleanOperator>;
dropdownClassName?: string;
/**
* Keys that have duration values
*/
durationKeys?: Set<string>;
/**
* A list of tags to exclude from the autocompletion list, for ex environment may be excluded
* because we don't want to treat environment as a tag in some places such
* as the stream view where it is a top level concept
*/
excludedTags?: string[];
/**
* A function that returns a warning message for a given filter key
* will only show a render a warning if the value is truthy
*/
// @ts-expect-error TS(7006): Parameter 'key' implicitly has an 'any' type.
getFilterWarning?: (key) => React.ReactNode;
/**
* List user's recent searches
*/
hasRecentSearches?: boolean;
/**
* Whether or not to highlight unsupported tags red
*/
highlightUnsupportedTags?: boolean;
/**
* Allows additional content to be played before the search bar and icon
*/
inlineLabel?: React.ReactNode;
/**
* Maximum height for the search dropdown menu
*/
maxMenuHeight?: number;
/**
* Used to enforce length on the query
*/
maxQueryLength?: number;
/**
* Maximum number of search items to display or a falsey value for no
* maximum
*/
maxSearchItems?: number;
/**
* While the data is unused, this list of members can be updated to
* trigger re-renders.
*/
members?: User[];
/**
* Extend search group items with additional props
* Useful for providing descriptions to field parents with many children
*/
mergeSearchGroupWith?: Record<string, SearchItem>;
/**
* Keys that have numeric values
*/
numericKeys?: Set<string>;
/**
* Called when the search input is blurred.
* Note that the input may be blurred when the user selects an autocomplete
* value - if you don't want that, onClose may be a better option.
*/
onBlur?: (value: string) => void;
/**
* Called when the search input changes
*/
onChange?: (value: string, e: React.ChangeEvent | React.ClipboardEvent) => void;
/**
* Called when the user has closed the search dropdown.
* Occurs on escape, tab, or clicking outside the component.
*/
onClose?: (value: string, additionalSearchBarState: {validSearch: boolean}) => void;
/**
* Get a list of recent searches for the current query
*/
onGetRecentSearches?: (query: string) => Promise<SearchItem[]>;
/**
* Get a list of tag values for the passed tag
*/
onGetTagValues?: (
tag: Tag,
query: string,
params: Record<PropertyKey, unknown>
) => Promise<string[]>;
/**
* Called on key down
*/
onKeyDown?: (evt: React.KeyboardEvent<HTMLTextAreaElement>) => void;
/**
* Called when a recent search is saved
*/
onSavedRecentSearch?: (query: string) => void;
/**
* Keys that have percentage values
*/
percentageKeys?: Set<string>;
/**
* Prepare query value before filtering dropdown items
*/
prepareQuery?: (query: string) => string;
/**
* Projects that the search bar queries over
*/
projectIds?: number[] | readonly number[];
/**
* Indicates the usage of the search bar for analytics
*/
searchSource?: string;
/**
* Keys that have size values
*/
sizeKeys?: Set<string>;
/**
* Type of supported tags
*/
supportedTagType?: ItemType;
/**
* Keys with text values that also allow additional operation like ">=" / "<=" / ">" / "<" / "=" / "!="
*/
textOperatorKeys?: Set<string>;
};
type State = {
/**
* Index of the focused search item
*/
activeSearchItem: number;
flatSearchItems: SearchItem[];
inputHasFocus: boolean;
loading: boolean;
/**
* The number of actions that are not in the overflow menu.
*/
numActionsVisible: number;
/**
* The query parsed into an AST. If the query fails to parse this will be
* null.
*/
parsedQuery: ParseResult | null;
/**
* The current search query in the input
*/
query: string;
searchGroups: SearchGroup[];
/**
* The current search term (or 'key') that that we will be showing
* autocompletion for.
*/
searchTerm: string;
/**
* Boolean indicating if dropdown should be shown
*/
showDropdown: boolean;
tags: Record<string, string>;
/**
* Indicates that we have a query that we've already determined not to have
* any values. This is used to stop the autocompleter from querying if we
* know we will find nothing.
*/
noValueQuery?: string;
/**
* The query in the input since we last updated our autocomplete list.
*/
previousQuery?: string;
};
/**
* @deprecated use SearchQueryBuilder instead
*/
class DeprecatedSmartSearchBar extends Component<DefaultProps & Props, State> {
static defaultProps = {
id: 'smart-search-input',
includeLabel: true,
defaultQuery: '',
query: null,
onSearch: function () {},
name: 'query',
placeholder: t('Search for events, users, tags, and more'),
supportedTags: {},
defaultSearchItems: [[], []],
useFormWrapper: true,
savedSearchType: SavedSearchType.ISSUE,
fieldDefinitionGetter: getFieldDefinition,
} as DefaultProps;
state: State = {
query: this.initialQuery,
showDropdown: false,
parsedQuery: parseSearch(this.initialQuery, pickParserOptions(this.props)),
searchTerm: '',
searchGroups: [],
flatSearchItems: [],
activeSearchItem: -1,
tags: {},
inputHasFocus: false,
loading: false,
numActionsVisible: this.props.actionBarItems?.length ?? 0,
};
componentDidMount() {
if (!window.ResizeObserver) {
return;
}
if (this.containerRef.current === null) {
return;
}
this.inputResizeObserver = new ResizeObserver(this.updateActionsVisible);
this.inputResizeObserver.observe(this.containerRef.current);
}
componentDidUpdate(prevProps: Props) {
const {query, actionBarItems} = this.props;
const parserOptions = pickParserOptions(this.props);
const {query: lastQuery, actionBarItems: lastActionBar} = prevProps;
const prevParserOptions = pickParserOptions(prevProps);
if (query !== lastQuery && (defined(query) || defined(lastQuery))) {
this.setState(this.makeQueryState(addSpace(query ?? undefined)));
} else if (!isEqual(parserOptions, prevParserOptions)) {
// Re-parse query to apply new options (without resetting it to the query prop value)
this.setState(this.makeQueryState(this.state.query));
}
if (lastActionBar?.length !== actionBarItems?.length) {
this.setState({numActionsVisible: actionBarItems?.length ?? 0});
}
}
componentWillUnmount() {
this.inputResizeObserver?.disconnect();
this.updateAutoCompleteItems?.cancel();
document.removeEventListener('pointerup', this.onBackgroundPointerUp);
}
get initialQuery() {
const {query, defaultQuery} = this.props;
return query === null ? (defaultQuery ?? '') : addSpace(query);
}
makeQueryState(query: string) {
const additionalConfig: Partial<SearchConfig> = pickParserOptions(this.props);
return {
query,
parsedQuery: parseSearch(query, additionalConfig),
};
}
/**
* Ref to the search element itself
*/
searchInput = createRef<HTMLTextAreaElement>();
/**
* Ref to the search container
*/
containerRef = createRef<HTMLDivElement>();
/**
* Used to determine when actions should be moved to the action overflow menu
*/
inputResizeObserver: ResizeObserver | null = null;
/**
* Only closes the dropdown when pointer events occur outside of this component
*/
onBackgroundPointerUp = (e: PointerEvent) => {
if (this.containerRef.current?.contains(e.target as Node)) {
return;
}
this.close();
};
/**
* Updates the numActionsVisible count as the search bar is resized
*/
updateActionsVisible = (entries: ResizeObserverEntry[]) => {
if (entries.length === 0) {
return;
}
const entry = entries[0]!;
const {width} = entry.contentRect;
const actionCount = this.props.actionBarItems?.length ?? 0;
const numActionsVisible = Math.min(
actionCount,
Math.floor(Math.max(0, width - ACTION_OVERFLOW_WIDTH) / ACTION_OVERFLOW_STEPS)
);
if (this.state.numActionsVisible === numActionsVisible) {
return;
}
this.setState({numActionsVisible});
};
blur() {
if (!this.searchInput.current) {
return;
}
this.searchInput.current.blur();
this.close();
}
async doSearch() {
this.blur();
const query = removeSpace(this.state.query);
const {organization, savedSearchType, searchSource, projectIds} = this.props;
const searchType = savedSearchType === 0 ? 'issues' : 'events';
if (!this.hasValidSearch) {
trackAnalytics('search.search_with_invalid', {
organization,
query,
search_type: searchType,
search_source: searchSource,
});
return;
}
const {onSearch, onSavedRecentSearch, api} = this.props;
trackAnalytics('search.searched', {
organization,
query,
is_multi_project: isMultiProject(projectIds),
search_type: searchType,
search_source: searchSource,
});
// track the individual key-values filters in the search query
Object.entries(new MutableSearch(query).filters).forEach(([key, values]) => {
trackAnalytics('search.searched_filter', {
organization,
query,
key,
values,
is_multi_project: isMultiProject(projectIds),
search_type: searchType,
search_source: searchSource,
});
});
onSearch?.(query);
// Only save recent search query if we have a savedSearchType (also 0 is a valid value)
// Do not save empty string queries (i.e. if they clear search)
if (typeof savedSearchType === 'undefined' || !query) {
return;
}
try {
await saveRecentSearch(api, organization.slug, savedSearchType, query);
if (onSavedRecentSearch) {
onSavedRecentSearch(query);
}
} catch (err) {
// Silently capture errors if it fails to save
Sentry.captureException(err);
}
}
moveToNextToken = (filterTokens: Array<TokenResult<Token.FILTER>>) => {
const token = this.cursorToken;
if (this.searchInput.current && filterTokens.length > 0) {
maybeFocusInput(this.searchInput.current);
let offset = filterTokens[0]!.location.end.offset;
if (token) {
// @ts-expect-error: Mismatched types
const tokenIndex = filterTokens.indexOf(token);
if (tokenIndex !== -1 && tokenIndex + 1 < filterTokens.length) {
offset = filterTokens[tokenIndex + 1]!.location.end.offset;
}
}
this.searchInput.current.selectionStart = offset;
this.searchInput.current.selectionEnd = offset;
this.updateAutoCompleteItems();
}
};
deleteToken = () => {
const {query} = this.state;
const token = this.cursorToken ?? undefined;
const filterTokens = this.filterTokens;
const hasExecCommand = typeof document.execCommand === 'function';
if (token && filterTokens.length > 0) {
// @ts-expect-error: Mismatched types
const index = filterTokens.indexOf(token) ?? -1;
const newQuery =
// We trim to remove any remaining spaces
query.slice(0, token.location.start.offset).trim() +
(index > 0 && index < filterTokens.length - 1 ? ' ' : '') +
query.slice(token.location.end.offset).trim();
if (this.searchInput.current) {
// Only use exec command if exists
maybeFocusInput(this.searchInput.current);
this.searchInput.current.selectionStart = 0;
this.searchInput.current.selectionEnd = query.length;
// Because firefox doesn't support inserting an empty string, we insert a newline character instead
// But because of this, only on firefox, if you delete the last token you won't be able to undo.
if (
(navigator.userAgent.toLowerCase().includes('firefox') &&
newQuery.length === 0) ||
!hasExecCommand ||
!document.execCommand('insertText', false, newQuery)
) {
// This will run either when newQuery is empty on firefox or when execCommand fails.
this.updateQuery(newQuery);
}
}
}
};
negateToken = () => {
const {query} = this.state;
const token = this.cursorToken ?? undefined;
const hasExecCommand = typeof document.execCommand === 'function';
if (token && token.type === Token.FILTER) {
if (token.negated) {
if (this.searchInput.current) {
maybeFocusInput(this.searchInput.current);
const tokenCursorOffset = this.cursorPosition - token.key.location.start.offset;
// Select the whole token so we can replace it.
this.searchInput.current.selectionStart = token.location.start.offset;
this.searchInput.current.selectionEnd = token.location.end.offset;
// We can't call insertText with an empty string on Firefox, so we have to do this.
if (
!hasExecCommand ||
!document.execCommand('insertText', false, token.text.slice(1))
) {
// Fallback when execCommand fails
const newQuery =
query.slice(0, token.location.start.offset) +
query.slice(token.key.location.start.offset);
this.updateQuery(newQuery, this.cursorPosition - 1);
}
// Return the cursor to where it should be
const newCursorPosition = token.location.start.offset + tokenCursorOffset;
this.searchInput.current.selectionStart = newCursorPosition;
this.searchInput.current.selectionEnd = newCursorPosition;
}
} else {
if (this.searchInput.current) {
maybeFocusInput(this.searchInput.current);
const tokenCursorOffset = this.cursorPosition - token.key.location.start.offset;
this.searchInput.current.selectionStart = token.location.start.offset;
this.searchInput.current.selectionEnd = token.location.start.offset;
if (!hasExecCommand || !document.execCommand('insertText', false, '!')) {
// Fallback when execCommand fails
const newQuery =
query.slice(0, token.key.location.start.offset) +
'!' +
query.slice(token.key.location.start.offset);
this.updateQuery(newQuery, this.cursorPosition + 1);
}
// Return the cursor to where it should be, +1 for the ! character we added
const newCursorPosition = token.location.start.offset + tokenCursorOffset + 1;
this.searchInput.current.selectionStart = newCursorPosition;
this.searchInput.current.selectionEnd = newCursorPosition;
}
}
}
};
logShortcutEvent = (shortcutType: ShortcutType, shortcutMethod: 'click' | 'hotkey') => {
const {searchSource, savedSearchType, organization} = this.props;
const {query} = this.state;
trackAnalytics('search.shortcut_used', {
organization,
search_type: savedSearchType === 0 ? 'issues' : 'events',
search_source: searchSource,
shortcut_method: shortcutMethod,
shortcut_type: shortcutType,
query,
});
};
logDocsOpenedEvent = () => {
const {searchSource, savedSearchType, organization} = this.props;
trackAnalytics('search.docs_opened', {
organization,
search_type: savedSearchType === 0 ? 'issues' : 'events',
search_source: searchSource,
query: this.state.query,
});
};
runShortcutOnClick = (shortcut: Shortcut) => {
this.runShortcut(shortcut);
this.logShortcutEvent(shortcut.shortcutType, 'click');
};
runShortcutOnHotkeyPress = (shortcut: Shortcut) => {
this.runShortcut(shortcut);
this.logShortcutEvent(shortcut.shortcutType, 'hotkey');
};
runShortcut = (shortcut: Shortcut) => {
const token = this.cursorToken;
const filterTokens = this.filterTokens;
const {shortcutType, canRunShortcut} = shortcut;
if (canRunShortcut(token, this.filterTokens.length)) {
switch (shortcutType) {
case ShortcutType.DELETE: {
this.deleteToken();
break;
}
case ShortcutType.NEGATE: {
this.negateToken();
break;
}
case ShortcutType.NEXT: {
this.moveToNextToken(filterTokens);
break;
}
case ShortcutType.PREVIOUS: {
this.moveToNextToken(filterTokens.reverse());
break;
}
default:
break;
}
}
};
onSubmit = (evt: React.FormEvent) => {
evt.preventDefault();
this.doSearch();
};
clearSearch = () => {
this.setState(this.makeQueryState(''), () => {
this.close();
this.props.onSearch?.(this.state.query);
});
};
close = () => {
this.setState({showDropdown: false});
this.props.onClose?.(this.state.query, {validSearch: this.hasValidSearch});
document.removeEventListener('pointerup', this.onBackgroundPointerUp);
};
open = () => {
this.setState({showDropdown: true});
document.addEventListener('pointerup', this.onBackgroundPointerUp);
};
onQueryFocus = () => {
Sentry.withScope(scope => {
const span = Sentry.startInactiveSpan({
name: 'smart_search_bar.open',
op: 'ui.render',
forceTransaction: true,
});
if (!span) {
return;
}
if (typeof window.requestIdleCallback === 'function') {
scope.setTag('finish_strategy', 'idle_callback');
window.requestIdleCallback(() => {
span.end();
});
} else {
scope.setTag('finish_strategy', 'timeout');
setTimeout(() => {
span.end();
}, 1_000);
}
});
this.open();
this.setState({inputHasFocus: true});
};
onQueryBlur = (e: React.FocusEvent<HTMLTextAreaElement>) => {
this.setState({inputHasFocus: false});
this.props.onBlur?.(e.target.value);
};
onQueryChange = (evt: React.ChangeEvent<HTMLTextAreaElement>) => {
const query = evt.target.value.replace('\n', '');
this.setState(this.makeQueryState(query), this.updateAutoCompleteItems);
this.props.onChange?.(evt.target.value, evt);
};
/**
* Prevent pasting extra spaces from formatted text
*/
onPaste = (evt: React.ClipboardEvent<HTMLTextAreaElement>) => {
// Cancel paste
evt.preventDefault();
// Get text representation of clipboard
const text = evt.clipboardData.getData('text/plain').replace('\n', '').trim();
// Create new query
const currentQuery = this.state.query;
const cursorPosStart = this.searchInput.current!.selectionStart;
const cursorPosEnd = this.searchInput.current!.selectionEnd;
const textBefore = currentQuery.substring(0, cursorPosStart);
const textAfter = currentQuery.substring(cursorPosEnd, currentQuery.length);
const mergedText = `${textBefore}${text}${textAfter}`;
// Insert text manually
this.setState(this.makeQueryState(mergedText), () => {
this.updateAutoCompleteItems();
// Update cursor position after updating text
const newCursorPosition = cursorPosStart + text.length;
this.searchInput.current!.selectionStart = newCursorPosition;
this.searchInput.current!.selectionEnd = newCursorPosition;
});
if (typeof this.props.onChange === 'function') {
this.props.onChange(mergedText, evt);
}
};
onInputClick = () => {
this.open();
this.updateAutoCompleteItems();
};
/**
* Handle keyboard navigation
*/
onKeyDown = (evt: React.KeyboardEvent<HTMLTextAreaElement>) => {
const {onKeyDown} = this.props;
const {key} = evt;
onKeyDown?.(evt);
const hasSearchGroups = this.state.searchGroups.length > 0;
const isSelectingDropdownItems = this.state.activeSearchItem !== -1;
if (!this.state.showDropdown && key !== 'Escape') {
this.open();
}
if ((key === 'ArrowDown' || key === 'ArrowUp') && hasSearchGroups) {
evt.preventDefault();
const {flatSearchItems, activeSearchItem} = this.state;
let searchGroups = [...this.state.searchGroups];
const currIndex = isSelectingDropdownItems ? activeSearchItem : 0;
const totalItems = flatSearchItems.length;
// Move the selected index up/down
const nextActiveSearchItem =
key === 'ArrowUp'
? (currIndex - 1 + totalItems) % totalItems
: isSelectingDropdownItems
? (currIndex + 1) % totalItems
: 0;
// Clear previous selection
const prevItem = flatSearchItems[currIndex]!;
searchGroups = getSearchGroupWithItemMarkedActive(searchGroups, prevItem, false);
// Set new selection
const activeItem = flatSearchItems[nextActiveSearchItem];
searchGroups = getSearchGroupWithItemMarkedActive(searchGroups, activeItem!, true);
this.setState({searchGroups, activeSearchItem: nextActiveSearchItem});
}
if (
(key === 'Tab' || key === 'Enter') &&
isSelectingDropdownItems &&
hasSearchGroups
) {
evt.preventDefault();
const {activeSearchItem, flatSearchItems} = this.state;
const item = flatSearchItems[activeSearchItem];
if (item) {
if (item.callback) {
item.callback();
} else {
this.onAutoComplete(item.value ?? '', item);
}
}
return;
}