-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
SourcegraphWebApp.tsx
498 lines (454 loc) · 23.7 KB
/
SourcegraphWebApp.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
import 'focus-visible'
import * as React from 'react'
import { ApolloProvider } from '@apollo/client'
import { createBrowserHistory } from 'history'
import ServerIcon from 'mdi-react/ServerIcon'
import { Route, Router } from 'react-router'
import { CompatRouter } from 'react-router-dom-v5-compat'
import { combineLatest, from, Subscription, fromEvent, of, Subject, Observable } from 'rxjs'
import { distinctUntilChanged, first, map, startWith, switchMap } from 'rxjs/operators'
import * as uuid from 'uuid'
import { logger } from '@sourcegraph/common'
import { GraphQLClient, HTTPStatusError } from '@sourcegraph/http-client'
import { SharedSpanName, TraceSpanProvider } from '@sourcegraph/observability-client'
import {
fetchAutoDefinedSearchContexts,
getUserSearchContextNamespaces,
SearchContextProps,
fetchSearchContexts,
fetchSearchContext,
fetchSearchContextBySpec,
createSearchContext,
updateSearchContext,
deleteSearchContext,
isSearchContextSpecAvailable,
getAvailableSearchContextSpecOrDefault,
SearchQueryStateStoreProvider,
} from '@sourcegraph/search'
import { NotificationType } from '@sourcegraph/shared/src/api/extension/extensionHostApi'
import { FetchFileParameters, fetchHighlightedFileLineRanges } from '@sourcegraph/shared/src/backend/file'
import { setCodeIntelSearchContext } from '@sourcegraph/shared/src/codeintel/searchContext'
import { Controller as ExtensionsController } from '@sourcegraph/shared/src/extensions/controller'
import { createController as createExtensionsController } from '@sourcegraph/shared/src/extensions/createLazyLoadedController'
import { createNoopController } from '@sourcegraph/shared/src/extensions/createNoopLoadedController'
import { BrandedNotificationItemStyleProps } from '@sourcegraph/shared/src/notifications/NotificationItem'
import { Notifications } from '@sourcegraph/shared/src/notifications/Notifications'
import { PlatformContext } from '@sourcegraph/shared/src/platform/context'
import { ShortcutProvider } from '@sourcegraph/shared/src/react-shortcuts'
import { FilterType } from '@sourcegraph/shared/src/search/query/filters'
import { filterExists } from '@sourcegraph/shared/src/search/query/validate'
import { aggregateStreamingSearch } from '@sourcegraph/shared/src/search/stream'
import { EMPTY_SETTINGS_CASCADE, SettingsCascadeProps } from '@sourcegraph/shared/src/settings/settings'
import { TemporarySettingsProvider } from '@sourcegraph/shared/src/settings/temporary/TemporarySettingsProvider'
import { TemporarySettingsStorage } from '@sourcegraph/shared/src/settings/temporary/TemporarySettingsStorage'
import { globbingEnabledFromSettings } from '@sourcegraph/shared/src/util/globbing'
import { FeedbackText, setLinkComponent, RouterLink, WildcardThemeContext, WildcardTheme } from '@sourcegraph/wildcard'
import { authenticatedUser, AuthenticatedUser } from './auth'
import { getWebGraphQLClient } from './backend/graphql'
import { BatchChangesProps, isBatchChangesExecutionEnabled } from './batches'
import type { CodeIntelligenceProps } from './codeintel'
import { CodeMonitoringProps } from './codeMonitoring'
import { ComponentsComposer } from './components/ComponentsComposer'
import { ErrorBoundary } from './components/ErrorBoundary'
import { HeroPage } from './components/HeroPage'
import type { ExtensionAreaRoute } from './extensions/extension/ExtensionArea'
import type { ExtensionAreaHeaderNavItem } from './extensions/extension/ExtensionAreaHeader'
import type { ExtensionsAreaRoute } from './extensions/ExtensionsArea'
import type { ExtensionsAreaHeaderActionButton } from './extensions/ExtensionsAreaHeader'
import { FeatureFlagsProvider } from './featureFlags/FeatureFlagsProvider'
import type { CodeInsightsProps } from './insights/types'
import { Layout, LayoutProps } from './Layout'
import { BlockInput, NotebookProps } from './notebooks'
import { createNotebook } from './notebooks/backend'
import { blockToGQLInput } from './notebooks/serialize'
import type { OrgAreaRoute } from './org/area/OrgArea'
import type { OrgAreaHeaderNavItem } from './org/area/OrgHeader'
import type { OrgSettingsAreaRoute } from './org/settings/OrgSettingsArea'
import type { OrgSettingsSidebarItems } from './org/settings/OrgSettingsSidebar'
import { createPlatformContext } from './platform/context'
import type { RepoContainerRoute } from './repo/RepoContainer'
import type { RepoHeaderActionButton } from './repo/RepoHeader'
import type { RepoRevisionContainerRoute } from './repo/RepoRevisionContainer'
import type { RepoSettingsAreaRoute } from './repo/settings/RepoSettingsArea'
import type { RepoSettingsSideBarGroup } from './repo/settings/RepoSettingsSidebar'
import type { LayoutRouteProps } from './routes'
import { EnterprisePageRoutes } from './routes.constants'
import { parseSearchURL, getQueryStateFromLocation } from './search'
import { SearchResultsCacheProvider } from './search/results/SearchResultsCacheProvider'
import type { SiteAdminAreaRoute } from './site-admin/SiteAdminArea'
import type { SiteAdminSideBarGroups } from './site-admin/SiteAdminSidebar'
import { CodeHostScopeProvider } from './site/CodeHostScopeAlerts/CodeHostScopeProvider'
import {
setQueryStateFromSettings,
setExperimentalFeaturesFromSettings,
getExperimentalFeatures,
useNavbarQueryState,
observeStore,
useExperimentalFeatures,
} from './stores'
import { setQueryStateFromURL } from './stores/navbarSearchQueryState'
import { eventLogger } from './tracking/eventLogger'
import type { UserAreaRoute } from './user/area/UserArea'
import type { UserAreaHeaderNavItem } from './user/area/UserAreaHeader'
import type { UserSettingsAreaRoute } from './user/settings/UserSettingsArea'
import type { UserSettingsSidebarItems } from './user/settings/UserSettingsSidebar'
import { UserSessionStores } from './UserSessionStores'
import { observeLocation } from './util/location'
import { siteSubjectNoAdmin, viewerSubjectFromSettings } from './util/settings'
import styles from './SourcegraphWebApp.module.scss'
export interface SourcegraphWebAppProps
extends CodeIntelligenceProps,
CodeInsightsProps,
Pick<BatchChangesProps, 'batchChangesEnabled'>,
Pick<SearchContextProps, 'searchContextsEnabled'>,
NotebookProps,
CodeMonitoringProps {
extensionAreaRoutes: readonly ExtensionAreaRoute[]
extensionAreaHeaderNavItems: readonly ExtensionAreaHeaderNavItem[]
extensionsAreaRoutes?: readonly ExtensionsAreaRoute[]
extensionsAreaHeaderActionButtons?: readonly ExtensionsAreaHeaderActionButton[]
siteAdminAreaRoutes: readonly SiteAdminAreaRoute[]
siteAdminSideBarGroups: SiteAdminSideBarGroups
siteAdminOverviewComponents: readonly React.ComponentType<React.PropsWithChildren<unknown>>[]
userAreaHeaderNavItems: readonly UserAreaHeaderNavItem[]
userAreaRoutes: readonly UserAreaRoute[]
userSettingsSideBarItems: UserSettingsSidebarItems
userSettingsAreaRoutes: readonly UserSettingsAreaRoute[]
orgSettingsSideBarItems: OrgSettingsSidebarItems
orgSettingsAreaRoutes: readonly OrgSettingsAreaRoute[]
orgAreaHeaderNavItems: readonly OrgAreaHeaderNavItem[]
orgAreaRoutes: readonly OrgAreaRoute[]
repoContainerRoutes: readonly RepoContainerRoute[]
repoRevisionContainerRoutes: readonly RepoRevisionContainerRoute[]
repoHeaderActionButtons: readonly RepoHeaderActionButton[]
repoSettingsAreaRoutes: readonly RepoSettingsAreaRoute[]
repoSettingsSidebarGroups: readonly RepoSettingsSideBarGroup[]
routes: readonly LayoutRouteProps<any>[]
}
interface SourcegraphWebAppState extends SettingsCascadeProps {
error?: Error
/**
* The currently authenticated user:
* - `undefined` until `CurrentAuthState` query completion.
* - `AuthenticatedUser` if the viewer is authenticated.
* - `null` if the viewer is anonymous.
*/
authenticatedUser?: AuthenticatedUser | null
/** GraphQL client initialized asynchronously to restore persisted cache. */
graphqlClient?: GraphQLClient
temporarySettingsStorage?: TemporarySettingsStorage
viewerSubject: LayoutProps['viewerSubject']
selectedSearchContextSpec?: string
defaultSearchContextSpec: string
/**
* Whether globbing is enabled for filters.
*/
globbing: boolean
}
const notificationStyles: BrandedNotificationItemStyleProps = {
notificationItemVariants: {
[NotificationType.Log]: 'secondary',
[NotificationType.Success]: 'success',
[NotificationType.Info]: 'info',
[NotificationType.Warning]: 'warning',
[NotificationType.Error]: 'danger',
},
}
const LAST_SEARCH_CONTEXT_KEY = 'sg-last-search-context'
const WILDCARD_THEME: WildcardTheme = {
isBranded: true,
}
setLinkComponent(RouterLink)
const history = createBrowserHistory()
/**
* The root component.
*/
export class SourcegraphWebApp extends React.Component<
React.PropsWithChildren<SourcegraphWebAppProps>,
SourcegraphWebAppState
> {
private readonly subscriptions = new Subscription()
private readonly userRepositoriesUpdates = new Subject<void>()
private readonly platformContext: PlatformContext = createPlatformContext()
private readonly extensionsController: ExtensionsController | null = window.context.enableLegacyExtensions
? createExtensionsController(this.platformContext)
: createNoopController(this.platformContext)
constructor(props: SourcegraphWebAppProps) {
super(props)
if (this.extensionsController !== null) {
this.subscriptions.add(this.extensionsController)
}
this.state = {
settingsCascade: EMPTY_SETTINGS_CASCADE,
viewerSubject: siteSubjectNoAdmin(),
defaultSearchContextSpec: 'global', // global is default for now, user will be able to change this at some point
globbing: false,
}
}
public componentDidMount(): void {
const parsedSearchURL = parseSearchURL(window.location.search)
const parsedSearchQuery = parsedSearchURL.query || ''
document.documentElement.classList.add('theme')
getWebGraphQLClient()
.then(graphqlClient => {
this.setState({
graphqlClient,
temporarySettingsStorage: new TemporarySettingsStorage(
graphqlClient,
window.context.isAuthenticatedUser
),
})
})
.catch(error => {
logger.error('Error initializing GraphQL client', error)
})
this.subscriptions.add(
combineLatest([
from(this.platformContext.settings),
// Start with `undefined` while we don't know if the viewer is authenticated or not.
authenticatedUser.pipe(startWith(undefined)),
]).subscribe(
([settingsCascade, authenticatedUser]) => {
setExperimentalFeaturesFromSettings(settingsCascade)
setQueryStateFromSettings(settingsCascade)
this.setState({
settingsCascade,
authenticatedUser,
globbing: globbingEnabledFromSettings(settingsCascade),
viewerSubject: viewerSubjectFromSettings(settingsCascade, authenticatedUser),
})
},
() => this.setState({ authenticatedUser: null })
)
)
/**
* Listens for uncaught 401 errors when a user when a user was previously authenticated.
*
* Don't subscribe to this event when there wasn't an authenticated user,
* as it could lead to an infinite loop of 401 -> reload -> 401
*/
this.subscriptions.add(
authenticatedUser
.pipe(
switchMap(authenticatedUser =>
authenticatedUser ? fromEvent<ErrorEvent>(window, 'error') : of(null)
)
)
.subscribe(event => {
if (event?.error instanceof HTTPStatusError && event.error.status === 401) {
location.reload()
}
})
)
if (parsedSearchQuery && !filterExists(parsedSearchQuery, FilterType.context)) {
// If a context filter does not exist in the query, we have to switch the selected context
// to global to match the UI with the backend semantics (if no context is specified in the query,
// the query is run in global context).
this.setSelectedSearchContextSpec('global')
}
if (!parsedSearchQuery) {
// If no query is present (e.g. search page, settings page), select the last saved
// search context from localStorage as currently selected search context.
const lastSelectedSearchContextSpec = localStorage.getItem(LAST_SEARCH_CONTEXT_KEY) || 'global'
this.setSelectedSearchContextSpec(lastSelectedSearchContextSpec)
}
this.setWorkspaceSearchContext(this.state.selectedSearchContextSpec).catch(error => {
logger.error('Error sending search context to extensions!', error)
})
// Update search query state whenever the URL changes
this.subscriptions.add(
getQueryStateFromLocation({
location: observeLocation(history).pipe(startWith(history.location)),
showSearchContext: observeStore(useExperimentalFeatures).pipe(
// We use true here because search contexts are enabled by
// default
map(([features]) => features.showSearchContext ?? true),
startWith(true),
distinctUntilChanged()
),
isSearchContextAvailable: (searchContext: string) =>
this.props.searchContextsEnabled
? isSearchContextSpecAvailable({ spec: searchContext, platformContext: this.platformContext })
.pipe(first())
.toPromise()
: Promise.resolve(false),
}).subscribe(parsedSearchURLAndContext => {
if (parsedSearchURLAndContext.query) {
// Only override filters and update query from URL if there
// is a search query.
if (
parsedSearchURLAndContext.searchContextSpec &&
parsedSearchURLAndContext.searchContextSpec !== this.state.selectedSearchContextSpec
) {
this.setSelectedSearchContextSpec(parsedSearchURLAndContext.searchContextSpec)
}
setQueryStateFromURL(parsedSearchURLAndContext, parsedSearchURLAndContext.processedQuery)
}
})
)
this.userRepositoriesUpdates.next()
}
public componentWillUnmount(): void {
this.subscriptions.unsubscribe()
}
public render(): React.ReactNode {
if (window.pageError && window.pageError.statusCode !== 404) {
const statusCode = window.pageError.statusCode
const statusText = window.pageError.statusText
const errorMessage = window.pageError.error
const errorID = window.pageError.errorID
let subtitle: JSX.Element | undefined
if (errorID) {
subtitle = <FeedbackText headerText="Sorry, there's been a problem." />
}
if (errorMessage) {
subtitle = (
<div className={styles.error}>
{subtitle}
{subtitle && <hr className="my-3" />}
<pre>{errorMessage}</pre>
</div>
)
} else {
subtitle = <div className={styles.error}>{subtitle}</div>
}
return <HeroPage icon={ServerIcon} title={`${statusCode}: ${statusText}`} subtitle={subtitle} />
}
const { authenticatedUser, graphqlClient, temporarySettingsStorage } = this.state
if (authenticatedUser === undefined || graphqlClient === undefined || temporarySettingsStorage === undefined) {
return null
}
const { children, ...props } = this.props
return (
<ComponentsComposer
components={[
// `ComponentsComposer` provides children via `React.cloneElement`.
/* eslint-disable react/no-children-prop, react/jsx-key */
<ApolloProvider client={graphqlClient} children={undefined} />,
<WildcardThemeContext.Provider value={WILDCARD_THEME} />,
<ErrorBoundary location={null} />,
<TraceSpanProvider name={SharedSpanName.AppMount} />,
<FeatureFlagsProvider />,
<ShortcutProvider />,
<TemporarySettingsProvider temporarySettingsStorage={temporarySettingsStorage} />,
<SearchResultsCacheProvider />,
<SearchQueryStateStoreProvider useSearchQueryState={useNavbarQueryState} />,
/* eslint-enable react/no-children-prop, react/jsx-key */
]}
>
<Router history={history} key={0}>
<CompatRouter>
<Route
path="/"
render={routeComponentProps => (
<CodeHostScopeProvider authenticatedUser={authenticatedUser}>
<Layout
{...props}
{...routeComponentProps}
authenticatedUser={authenticatedUser}
viewerSubject={this.state.viewerSubject}
settingsCascade={this.state.settingsCascade}
batchChangesEnabled={this.props.batchChangesEnabled}
batchChangesExecutionEnabled={isBatchChangesExecutionEnabled(
this.state.settingsCascade
)}
batchChangesWebhookLogsEnabled={window.context.batchChangesWebhookLogsEnabled}
// Search query
fetchHighlightedFileLineRanges={this.fetchHighlightedFileLineRanges}
// Extensions
platformContext={this.platformContext}
extensionsController={this.extensionsController}
telemetryService={eventLogger}
isSourcegraphDotCom={window.context.sourcegraphDotComMode}
searchContextsEnabled={this.props.searchContextsEnabled}
selectedSearchContextSpec={this.getSelectedSearchContextSpec()}
setSelectedSearchContextSpec={this.setSelectedSearchContextSpec}
getUserSearchContextNamespaces={getUserSearchContextNamespaces}
fetchAutoDefinedSearchContexts={fetchAutoDefinedSearchContexts}
fetchSearchContexts={fetchSearchContexts}
fetchSearchContextBySpec={fetchSearchContextBySpec}
fetchSearchContext={fetchSearchContext}
createSearchContext={createSearchContext}
updateSearchContext={updateSearchContext}
deleteSearchContext={deleteSearchContext}
isSearchContextSpecAvailable={isSearchContextSpecAvailable}
defaultSearchContextSpec={this.state.defaultSearchContextSpec}
globbing={this.state.globbing}
streamSearch={aggregateStreamingSearch}
onCreateNotebookFromNotepad={this.onCreateNotebook}
/>
</CodeHostScopeProvider>
)}
/>
</CompatRouter>
</Router>
{this.extensionsController !== null && window.context.enableLegacyExtensions ? (
<Notifications
key={2}
extensionsController={this.extensionsController}
notificationItemStyleProps={notificationStyles}
/>
) : null}
<UserSessionStores />
</ComponentsComposer>
)
}
private getSelectedSearchContextSpec = (): string | undefined =>
getExperimentalFeatures().showSearchContext ? this.state.selectedSearchContextSpec : undefined
private setSelectedSearchContextSpec = (spec: string): void => {
if (!this.props.searchContextsEnabled) {
return
}
const { defaultSearchContextSpec } = this.state
this.subscriptions.add(
getAvailableSearchContextSpecOrDefault({
spec,
defaultSpec: defaultSearchContextSpec,
platformContext: this.platformContext,
}).subscribe(availableSearchContextSpecOrDefault => {
this.setState({ selectedSearchContextSpec: availableSearchContextSpecOrDefault })
localStorage.setItem(LAST_SEARCH_CONTEXT_KEY, availableSearchContextSpecOrDefault)
this.setWorkspaceSearchContext(availableSearchContextSpecOrDefault).catch(error => {
logger.error('Error sending search context to extensions', error)
})
})
)
}
private async setWorkspaceSearchContext(spec: string | undefined): Promise<void> {
// NOTE(2022-09-08) Inform the inlined code from
// sourcegraph/code-intel-extensions about the change of search context.
// The old extension code previously accessed this information from the
// 'sourcegraph' npm package, and updating the context like this was the
// simplest solution to mirror the old behavior while deprecating
// extensions on a tight deadline. It would be nice to properly pass
// around this via React state in the future.
setCodeIntelSearchContext(spec)
if (this.extensionsController === null) {
return
}
const extensionHostAPI = await this.extensionsController.extHostAPI
await extensionHostAPI.setSearchContext(spec)
}
private onCreateNotebook = (blocks: BlockInput[]): void => {
if (!this.state.authenticatedUser) {
return
}
this.subscriptions.add(
createNotebook({
notebook: {
title: 'New Notebook',
blocks: blocks.map(block => blockToGQLInput({ id: uuid.v4(), ...block })),
public: false,
namespace: this.state.authenticatedUser.id,
},
}).subscribe(createdNotebook => {
history.push(EnterprisePageRoutes.Notebook.replace(':id', createdNotebook.id))
})
)
}
private fetchHighlightedFileLineRanges = (
parameters: FetchFileParameters,
force?: boolean | undefined
): Observable<string[][]> =>
fetchHighlightedFileLineRanges({ ...parameters, platformContext: this.platformContext }, force)
}