-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
StreamingSearchResults.tsx
435 lines (393 loc) · 18.5 KB
/
StreamingSearchResults.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
import { useCallback, useEffect, useMemo, useState, FC } from 'react'
import classNames from 'classnames'
import * as H from 'history'
import { useHistory } from 'react-router'
import { Observable } from 'rxjs'
import { asError } from '@sourcegraph/common'
import { QueryUpdate, SearchContextProps, SearchMode } from '@sourcegraph/search'
import { StreamingProgress, StreamingSearchResultsList } from '@sourcegraph/search-ui'
import { FetchFileParameters } from '@sourcegraph/shared/src/backend/file'
import { FilePrefetcher } from '@sourcegraph/shared/src/components/PrefetchableFile'
import { ExtensionsControllerProps } from '@sourcegraph/shared/src/extensions/controller'
import { SearchPatternType } from '@sourcegraph/shared/src/graphql-operations'
import { PlatformContextProps } from '@sourcegraph/shared/src/platform/context'
import { collectMetrics } from '@sourcegraph/shared/src/search/query/metrics'
import { sanitizeQueryForTelemetry, updateFilters } from '@sourcegraph/shared/src/search/query/transformer'
import { LATEST_VERSION, StreamSearchOptions } from '@sourcegraph/shared/src/search/stream'
import { SettingsCascadeProps } from '@sourcegraph/shared/src/settings/settings'
import { useTemporarySetting } from '@sourcegraph/shared/src/settings/temporary/useTemporarySetting'
import { TelemetryProps } from '@sourcegraph/shared/src/telemetry/telemetryService'
import { ThemeProps } from '@sourcegraph/shared/src/theme'
import { SearchStreamingProps } from '..'
import { AuthenticatedUser } from '../../auth'
import { PageTitle } from '../../components/PageTitle'
import { CodeInsightsProps } from '../../insights/types'
import { isCodeInsightsEnabled } from '../../insights/utils/is-code-insights-enabled'
import { fetchBlob, usePrefetchBlobFormat } from '../../repo/blob/backend'
import { SavedSearchModal } from '../../savedSearches/SavedSearchModal'
import { useExperimentalFeatures, useNavbarQueryState, useNotepad } from '../../stores'
import { GettingStartedTour } from '../../tour/GettingStartedTour'
import { submitSearch } from '../helpers'
import { DidYouMean } from '../suggestion/DidYouMean'
import { SmartSearch, smartSearchEvent } from '../suggestion/SmartSearch'
import { AggregationUIMode, SearchAggregationResult, useAggregationUIMode } from './components/aggregation'
import { SearchAlert } from './SearchAlert'
import { useCachedSearchResults } from './SearchResultsCacheProvider'
import { SearchResultsInfoBar } from './SearchResultsInfoBar'
import { SearchFiltersSidebar } from './sidebar/SearchFiltersSidebar'
import styles from './StreamingSearchResults.module.scss'
export interface StreamingSearchResultsProps
extends SearchStreamingProps,
Pick<SearchContextProps, 'selectedSearchContextSpec' | 'searchContextsEnabled'>,
SettingsCascadeProps,
ExtensionsControllerProps<'executeCommand' | 'extHostAPI'>,
PlatformContextProps<'settings' | 'requestGraphQL' | 'sourcegraphURL'>,
TelemetryProps,
ThemeProps,
CodeInsightsProps {
authenticatedUser: AuthenticatedUser | null
location: H.Location
history: H.History
isSourcegraphDotCom: boolean
fetchHighlightedFileLineRanges: (parameters: FetchFileParameters, force?: boolean) => Observable<string[][]>
}
export const StreamingSearchResults: FC<StreamingSearchResultsProps> = props => {
const {
streamSearch,
location,
authenticatedUser,
telemetryService,
codeInsightsEnabled,
isSourcegraphDotCom,
extensionsController,
} = props
const history = useHistory()
// Feature flags
const enableCodeMonitoring = useExperimentalFeatures(features => features.codeMonitoring ?? false)
const showSearchContext = useExperimentalFeatures(features => features.showSearchContext ?? false)
const prefetchFileEnabled = useExperimentalFeatures(features => features.enableSearchFilePrefetch ?? false)
const prefetchBlobFormat = usePrefetchBlobFormat()
const [sidebarCollapsed, setSidebarCollapsed] = useTemporarySetting('search.sidebar.collapsed', false)
// Global state
const caseSensitive = useNavbarQueryState(state => state.searchCaseSensitivity)
const patternType = useNavbarQueryState(state => state.searchPatternType)
const searchMode = useNavbarQueryState(state => state.searchMode)
const liveQuery = useNavbarQueryState(state => state.queryState.query)
const submittedURLQuery = useNavbarQueryState(state => state.searchQueryFromURL)
const setQueryState = useNavbarQueryState(state => state.setQueryState)
const submitQuerySearch = useNavbarQueryState(state => state.submitSearch)
const [aggregationUIMode] = useAggregationUIMode()
// Local state
const [allExpanded, setAllExpanded] = useState(false)
const [showSavedSearchModal, setShowSavedSearchModal] = useState(false)
const [showMobileSidebar, setShowMobileSidebar] = useState(false)
// Derived state
const extensionHostAPI =
extensionsController !== null && window.context.enableLegacyExtensions ? extensionsController.extHostAPI : null
const trace = useMemo(() => new URLSearchParams(location.search).get('trace') ?? undefined, [location.search])
const featureOverrides = useMemo(() => new URLSearchParams(location.search).getAll('feat') ?? [], [location.search])
const options: StreamSearchOptions = useMemo(
() => ({
version: LATEST_VERSION,
patternType: patternType ?? SearchPatternType.standard,
caseSensitive,
trace,
featureOverrides,
searchMode: patternType === SearchPatternType.lucky ? SearchMode.SmartSearch : searchMode,
chunkMatches: true,
}),
[caseSensitive, patternType, searchMode, trace, featureOverrides]
)
const results = useCachedSearchResults(streamSearch, submittedURLQuery, options, extensionHostAPI, telemetryService)
const resultsFound = useMemo<boolean>(() => (results ? results.results.length > 0 : false), [results])
// Log view event on first load
useEffect(
() => {
telemetryService.logViewEvent('SearchResults')
},
// Only log view on initial load
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
)
// Log search query event when URL changes
useEffect(() => {
const metrics = submittedURLQuery ? collectMetrics(submittedURLQuery) : undefined
telemetryService.log(
'SearchResultsQueried',
{
code_search: {
query_data: {
query: metrics,
combined: submittedURLQuery,
empty: !submittedURLQuery,
},
},
},
{
code_search: {
query_data: {
// 🚨 PRIVACY: never provide any private query data in the
// { code_search: query_data: query } property,
// which is also potentially exported in pings data.
query: metrics,
// 🚨 PRIVACY: Only collect the full query string for unauthenticated users
// on Sourcegraph.com, and only after sanitizing to remove certain filters.
combined:
!authenticatedUser && isSourcegraphDotCom
? sanitizeQueryForTelemetry(submittedURLQuery)
: undefined,
empty: !submittedURLQuery,
},
},
}
)
// Only log when the query changes
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [submittedURLQuery])
// Log events when search completes or fails
useEffect(() => {
if (results?.state === 'complete') {
telemetryService.log('SearchResultsFetched', {
code_search: {
// 🚨 PRIVACY: never provide any private data in { code_search: { results } }.
results: {
results_count: results.results.length,
any_cloning: results.progress.skipped.some(skipped => skipped.reason === 'repository-cloning'),
alert: results.alert ? results.alert.title : null,
},
},
})
if (results.results.length > 0) {
telemetryService.log('SearchResultsNonEmpty')
}
} else if (results?.state === 'error') {
telemetryService.log('SearchResultsFetchFailed', {
code_search: { error_message: asError(results.error).message },
})
}
}, [results, telemetryService])
useEffect(() => {
if (
(results?.alert?.kind === 'smart-search-additional-results' ||
results?.alert?.kind === 'smart-search-pure-results') &&
results?.alert?.title &&
results.alert.proposedQueries
) {
const events = smartSearchEvent(
results.alert.kind,
results.alert.title,
results.alert.proposedQueries.map(entry => entry.description || '')
)
for (const event of events) {
telemetryService.log(event)
}
}
}, [results, telemetryService])
// Reset expanded state when new search is started
useEffect(() => {
setAllExpanded(false)
}, [location.search])
useNotepad(
useMemo(
() =>
results?.state === 'complete'
? {
type: 'search',
query: submittedURLQuery,
caseSensitive,
patternType,
searchContext: props.selectedSearchContextSpec,
}
: null,
[results, submittedURLQuery, patternType, caseSensitive, props.selectedSearchContextSpec]
)
)
const onExpandAllResultsToggle = useCallback(() => {
setAllExpanded(oldValue => !oldValue)
telemetryService.log(allExpanded ? 'allResultsExpanded' : 'allResultsCollapsed')
}, [allExpanded, telemetryService])
const onSaveQueryClick = useCallback(() => setShowSavedSearchModal(true), [])
const onSaveQueryModalClose = useCallback(() => {
setShowSavedSearchModal(false)
telemetryService.log('SavedQueriesToggleCreating', { queries: { creating: false } })
}, [telemetryService])
// Reset expanded state when new search is started
useEffect(() => {
setAllExpanded(false)
}, [location.search])
const handleSidebarSearchSubmit = useCallback(
(updates: QueryUpdate[]) =>
submitQuerySearch(
{
selectedSearchContextSpec: props.selectedSearchContextSpec,
history,
source: 'filter',
},
updates
),
[submitQuerySearch, props.selectedSearchContextSpec, history]
)
const onSearchAgain = useCallback(
(additionalFilters: string[]) => {
telemetryService.log('SearchSkippedResultsAgainClicked')
submitSearch({
...props,
caseSensitive,
patternType,
query: applyAdditionalFilters(submittedURLQuery, additionalFilters),
source: 'excludedResults',
})
},
[submittedURLQuery, telemetryService, patternType, caseSensitive, props]
)
const handleSearchAggregationBarClick = (query: string): void => {
submitSearch({
...props,
caseSensitive,
patternType,
query,
source: 'nav',
})
}
// Show aggregation panel by default and only if search doesn't have any matches
// hide aggregation panel from the sidebar
const showAggregationPanel = results?.state === 'complete' ? (results?.results.length ?? 0) > 0 : true
const onDisableSmartSearch = useCallback(
() =>
submitSearch({
...props,
caseSensitive,
patternType: SearchPatternType.standard,
query: submittedURLQuery,
source: 'smartSearchDisabled',
}),
[caseSensitive, props, submittedURLQuery]
)
const prefetchFile: FilePrefetcher = useCallback(
params =>
fetchBlob({
...params,
format: prefetchBlobFormat,
}),
[prefetchBlobFormat]
)
return (
<div className={classNames(styles.container, sidebarCollapsed && styles.containerWithSidebarHidden)}>
<PageTitle key="page-title" title={submittedURLQuery} />
<SearchFiltersSidebar
liveQuery={liveQuery}
submittedURLQuery={submittedURLQuery}
patternType={patternType}
filters={results?.filters}
showAggregationPanel={showAggregationPanel}
selectedSearchContextSpec={props.selectedSearchContextSpec}
aggregationUIMode={aggregationUIMode}
settingsCascade={props.settingsCascade}
telemetryService={props.telemetryService}
caseSensitive={caseSensitive}
className={classNames(styles.sidebar, showMobileSidebar && styles.sidebarShowMobile)}
onNavbarQueryChange={setQueryState}
onSearchSubmit={handleSidebarSearchSubmit}
setSidebarCollapsed={setSidebarCollapsed}
>
<GettingStartedTour
className="mb-1"
isSourcegraphDotCom={props.isSourcegraphDotCom}
telemetryService={props.telemetryService}
isAuthenticated={!!props.authenticatedUser}
/>
</SearchFiltersSidebar>
{aggregationUIMode === AggregationUIMode.SearchPage && (
<SearchAggregationResult
query={submittedURLQuery}
patternType={patternType}
caseSensitive={caseSensitive}
aria-label="Aggregation results panel"
className={styles.contents}
onQuerySubmit={handleSearchAggregationBarClick}
telemetryService={props.telemetryService}
/>
)}
{aggregationUIMode !== AggregationUIMode.SearchPage && (
<>
<SearchResultsInfoBar
{...props}
patternType={patternType}
caseSensitive={caseSensitive}
query={submittedURLQuery}
enableCodeInsights={codeInsightsEnabled && isCodeInsightsEnabled(props.settingsCascade)}
enableCodeMonitoring={enableCodeMonitoring}
resultsFound={resultsFound}
className={styles.infobar}
allExpanded={allExpanded}
onExpandAllResultsToggle={onExpandAllResultsToggle}
onSaveQueryClick={onSaveQueryClick}
onShowMobileFiltersChanged={show => setShowMobileSidebar(show)}
sidebarCollapsed={!!sidebarCollapsed}
setSidebarCollapsed={setSidebarCollapsed}
stats={
<StreamingProgress
progress={results?.progress || { durationMs: 0, matchCount: 0, skipped: [] }}
state={results?.state || 'loading'}
onSearchAgain={onSearchAgain}
showTrace={!!trace}
/>
}
/>
<div className={styles.contents}>
<DidYouMean
telemetryService={props.telemetryService}
query={submittedURLQuery}
patternType={patternType}
caseSensitive={caseSensitive}
selectedSearchContextSpec={props.selectedSearchContextSpec}
/>
{results?.alert?.kind && (
<SmartSearch alert={results?.alert} onDisableSmartSearch={onDisableSmartSearch} />
)}
<GettingStartedTour.Info
className="mt-2 mb-3"
isSourcegraphDotCom={props.isSourcegraphDotCom}
/>
{showSavedSearchModal && (
<SavedSearchModal
{...props}
patternType={patternType}
query={submittedURLQuery}
authenticatedUser={authenticatedUser}
onDidCancel={onSaveQueryModalClose}
/>
)}
{results?.alert && !results?.alert.kind && (
<div className={classNames(styles.alertArea, 'mt-4')}>
<SearchAlert
alert={results.alert}
caseSensitive={caseSensitive}
patternType={patternType}
/>
</div>
)}
<StreamingSearchResultsList
{...props}
results={results}
allExpanded={allExpanded}
showSearchContext={showSearchContext}
assetsRoot={window.context?.assetsRoot || ''}
executedQuery={location.search}
prefetchFileEnabled={prefetchFileEnabled}
prefetchFile={prefetchFile}
/>
</div>
</>
)}
</div>
)
}
const applyAdditionalFilters = (query: string, additionalFilters: string[]): string => {
let newQuery = query
for (const filter of additionalFilters) {
const fieldValue = filter.split(':', 2)
newQuery = updateFilters(newQuery, fieldValue[0], fieldValue[1])
}
return newQuery
}