-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
TabbedPanelContent.tsx
428 lines (386 loc) · 18.2 KB
/
TabbedPanelContent.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
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { mdiClose } from '@mdi/js'
import classNames from 'classnames'
import { Remote } from 'comlink'
import { useHistory, useLocation } from 'react-router'
import { BehaviorSubject, from, Observable, combineLatest, of } from 'rxjs'
import { map, switchMap } from 'rxjs/operators'
import { ContributableMenu, Contributions, Evaluated } from '@sourcegraph/client-api'
import { MaybeLoadingResult } from '@sourcegraph/codeintellify'
import { isDefined, combineLatestOrDefault, isErrorLike } from '@sourcegraph/common'
import { Location } from '@sourcegraph/extension-api-types'
import { ActionsNavItems } from '@sourcegraph/shared/src/actions/ActionsNavItems'
import { wrapRemoteObservable } from '@sourcegraph/shared/src/api/client/api/common'
import { match } from '@sourcegraph/shared/src/api/client/types/textDocument'
import { ExtensionCodeEditor } from '@sourcegraph/shared/src/api/extension/api/codeEditor'
import { PanelViewData } from '@sourcegraph/shared/src/api/extension/extensionHostApi'
import { haveInitialExtensionsLoaded } from '@sourcegraph/shared/src/api/features'
import { FetchFileParameters } from '@sourcegraph/shared/src/backend/file'
import { ExtensionsControllerProps } from '@sourcegraph/shared/src/extensions/controller'
import { PlatformContextProps } from '@sourcegraph/shared/src/platform/context'
import { SettingsCascadeProps } from '@sourcegraph/shared/src/settings/settings'
import { TelemetryProps } from '@sourcegraph/shared/src/telemetry/telemetryService'
import { ThemeProps } from '@sourcegraph/shared/src/theme'
import {
Button,
useObservable,
Tab,
TabList,
TabPanel,
TabPanels,
Tabs,
Icon,
Tooltip,
useKeyboard,
} from '@sourcegraph/wildcard'
import { LegacyGroupByFileToggle } from './LegacyGroupByFileToggle'
import { MixPreciseAndSearchBasedReferencesToggle } from './MixPreciseAndSearchBasedReferencesToggle'
import { EmptyPanelView } from './views/EmptyPanelView'
import { ExtensionsLoadingPanelView } from './views/ExtensionsLoadingView'
import { PanelView } from './views/PanelView'
import styles from './TabbedPanelContent.module.scss'
interface TabbedPanelContentProps
extends ExtensionsControllerProps,
PlatformContextProps,
SettingsCascadeProps,
TelemetryProps,
ThemeProps {
repoName?: string
fetchHighlightedFileLineRanges: (parameters: FetchFileParameters, force?: boolean) => Observable<string[][]>
}
export interface PanelViewWithComponent extends PanelViewData {
/**
* The location provider whose results to render in the panel view.
*/
locationProvider?: Observable<MaybeLoadingResult<Location[]>>
/**
* Maximum number of results to show from locationProvider. If not set,
* MAXIMUM_LOCATION_RESULTS will be used.
*/
maxLocationResults?: number
/**
* The React element to render in the panel view.
*/
reactElement?: React.ReactNode
// Should the content of the panel be put inside a wrapper container with padding or not.
noWrapper?: boolean
// Should the panel be shown for the given `#tab=<ID>` in the URL?
matchesTabID?: (id: string) => boolean
}
/**
* A tab and corresponding content to display in the panel.
*/
interface TabbedPanelItem {
id: string
label: React.ReactNode
/**
* Controls the relative order of panel items. The items are laid out from highest priority (at the beginning)
* to lowest priority (at the end). The default is 0.
*/
priority: number
/** The content element to display when the tab is active. */
element: JSX.Element
/**
* Whether this panel contains a list of locations (from a location provider). This value is
* exposed to contributions as `panel.activeView.hasLocations`. It is true if there is a
* location provider (even if the result set is empty).
*/
hasLocations?: boolean
/** Callback that's triggered when the panel is selected */
trackTabClick: () => void
// Should the panel item be shown for the given `#tab=<ID>` in the URL?
matchesTabID?: (id: string) => boolean
}
export type BuiltinTabbedPanelView = Omit<PanelViewWithComponent, 'component' | 'id'>
const builtinTabbedPanelViewProviders = new BehaviorSubject<
Map<string, { id: string; provider: Observable<BuiltinTabbedPanelView | null> }>
>(new Map())
export const hierarchicalLocationViewHasResultContext = new BehaviorSubject<undefined | boolean>(undefined)
/**
* BuiltinTabbedPanelView defines which BuiltinTabbedPanelViews will be available.
*/
export interface BuiltinTabbedPanelDefinition {
id: string
provider: Observable<BuiltinTabbedPanelView | null>
}
/**
* React hook to add panel views from other components (panel views are typically
* contributed by Sourcegraph extensions)
*/
export function useBuiltinTabbedPanelViews(builtinPanels: BuiltinTabbedPanelDefinition[]): void {
useEffect(() => {
for (const builtinPanel of builtinPanels) {
builtinTabbedPanelViewProviders.value.set(builtinPanel.id, builtinPanel)
}
builtinTabbedPanelViewProviders.next(new Map([...builtinTabbedPanelViewProviders.value]))
return () => {
for (const builtinPanel of builtinPanels) {
builtinTabbedPanelViewProviders.value.delete(builtinPanel.id)
}
builtinTabbedPanelViewProviders.next(new Map([...builtinTabbedPanelViewProviders.value]))
}
}, [builtinPanels])
}
/**
* The panel, which is a tabbed component with contextual information. Components rendering the panel should
* generally use ResizablePanel, not Panel.
*
* Other components can contribute panel items to the panel with the `useBuildinPanelViews` hook.
*/
export const TabbedPanelContent = React.memo<TabbedPanelContentProps>(props => {
// Ensures that we don't show a misleading empty state when extensions haven't loaded yet.
const { extensionsController } = props
const areExtensionsReady = useObservable(
useMemo(
() =>
extensionsController !== null ? haveInitialExtensionsLoaded(extensionsController.extHostAPI) : of(true),
[extensionsController]
)
)
const isTabbedReferencesPanelEnabled =
!isErrorLike(props.settingsCascade.final) &&
props.settingsCascade.final !== null &&
props.settingsCascade.final['codeIntel.referencesPanel'] === 'tabbed'
const [tabIndex, setTabIndex] = useState(0)
const location = useLocation()
const { hash, pathname, search } = location
const history = useHistory()
const handlePanelClose = useCallback(() => history.replace(pathname), [history, pathname])
const [currentTabLabel, currentTabID] = hash.split('=')
const legacyHierarchicalLocationViewHasResult = useObservable(hierarchicalLocationViewHasResultContext)
const builtinTabbedPanels: PanelViewWithComponent[] | undefined = useObservable(
useMemo(
() =>
builtinTabbedPanelViewProviders.pipe(
switchMap(providers =>
combineLatestOrDefault(
[...providers].map(([id, { provider }]) =>
provider.pipe(map(view => (view ? { ...view, id, component: null } : null)))
)
)
),
map(views => views.filter(isDefined))
),
[]
)
)
const extensionPanels: PanelViewWithComponent[] | undefined = useObservable(
useMemo(() => {
if (extensionsController === null) {
return of([])
}
return from(extensionsController.extHostAPI).pipe(
switchMap(extensionHostAPI =>
combineLatest([
wrapRemoteObservable(extensionHostAPI.getPanelViews()),
wrapRemoteObservable(extensionHostAPI.getActiveViewComponentChanges()),
]).pipe(
switchMap(async ([panelViews, viewer]) => {
if ((await viewer?.type) !== 'CodeEditor') {
return undefined
}
const document = await (viewer as Remote<ExtensionCodeEditor>).document
return panelViews
.filter(panelView =>
panelView.selector !== null ? match(panelView.selector, document) : true
)
.filter(panelView =>
// If we use the tree-view reference panel
// we don't want to display additional
// 'implementations_' panels
!isTabbedReferencesPanelEnabled
? !panelView.component?.locationProvider?.startsWith('implementations_')
: true
)
.map((panelView: PanelViewWithComponent) => {
const locationProviderID = panelView.component?.locationProvider
const maxLocations = panelView.component?.maxLocationResults
if (locationProviderID) {
const panelViewWithProvider: PanelViewWithComponent = {
...panelView,
maxLocationResults: maxLocations,
locationProvider: wrapRemoteObservable(
extensionHostAPI.getActiveCodeEditorPosition()
).pipe(
switchMap(parameters => {
if (!parameters) {
return [{ isLoading: false, result: [] }]
}
return wrapRemoteObservable(
extensionHostAPI.getLocations(locationProviderID, parameters)
)
})
),
}
return panelViewWithProvider
}
return panelView
})
})
)
)
)
}, [isTabbedReferencesPanelEnabled, extensionsController])
)
const panelViews = useMemo(() => [...(builtinTabbedPanels || []), ...(extensionPanels || [])], [
builtinTabbedPanels,
extensionPanels,
])
const trackTabClick = useCallback((label: string) => props.telemetryService.log(`ReferencePanelClicked${label}`), [
props.telemetryService,
])
const items = useMemo(
() =>
panelViews
? panelViews
.map(
(panelView): TabbedPanelItem => ({
label: panelView.title,
id: panelView.id,
priority: panelView.priority,
element: <PanelView {...props} panelView={panelView} location={location} />,
hasLocations: !!panelView.locationProvider,
trackTabClick: () => trackTabClick(panelView.title),
matchesTabID: panelView.matchesTabID,
})
)
.sort((a, b) => b.priority - a.priority)
: [],
[location, panelViews, props, trackTabClick]
)
useKeyboard({ detectKeys: ['Escape'] }, handlePanelClose)
const handleActiveTab = useCallback(
(index: number): void => {
history.replace(`${pathname}${search}${currentTabLabel}=${items[index].id}`)
},
[currentTabLabel, history, items, pathname, search]
)
useEffect(() => {
setTabIndex(
items.findIndex(({ id, matchesTabID }) => (matchesTabID ? matchesTabID(currentTabID) : id === currentTabID))
)
}, [items, hash, currentTabID])
if (!areExtensionsReady) {
return <ExtensionsLoadingPanelView className={styles.panel} />
}
if (!items) {
return <EmptyPanelView className={styles.panel} />
}
const activeTab: TabbedPanelItem | undefined = items[tabIndex]
return (
<Tabs className={styles.panel} index={tabIndex} onChange={handleActiveTab}>
<TabList
wrapperClassName={classNames(styles.panelHeader, 'sticky-top')}
actions={
<div className="align-items-center d-flex">
<ul className="d-flex justify-content-end list-unstyled m-0 align-items-center">
{activeTab && (
<MixPreciseAndSearchBasedReferencesToggle
settingsCascade={props.settingsCascade}
platformContext={props.platformContext}
/>
)}
{activeTab && legacyHierarchicalLocationViewHasResult && (
<LegacyGroupByFileToggle
settingsCascade={props.settingsCascade}
platformContext={props.platformContext}
/>
)}
{activeTab && extensionsController !== null && (
<>
<ActionsNavItems
{...props}
extensionsController={extensionsController}
listItemClass="px-2 mx-2"
actionItemClass={classNames(
styles.actionItemUnconstrained,
'font-weight-medium'
)}
actionItemIconClass="icon-inline"
menu={ContributableMenu.PanelToolbar}
scope={{
type: 'panelView',
id: activeTab.id,
hasLocations: Boolean(activeTab.hasLocations),
}}
wrapInList={false}
location={location}
transformContributions={transformPanelContributions}
/>
</>
)}
</ul>
<Tooltip content="Close panel" placement="left">
<Button
onClick={handlePanelClose}
variant="icon"
className={classNames('ml-2', styles.dismissButton)}
title="Close panel"
>
<Icon aria-hidden={true} svgPath={mdiClose} />
</Button>
</Tooltip>
</div>
}
>
{items.map(({ label, id, trackTabClick }, index) => (
<Tab key={id} index={index}>
<span className="tablist-wrapper--tab-label" onClick={trackTabClick} role="none">
{label}
</span>
</Tab>
))}
</TabList>
<TabPanels>
{activeTab ? (
items.map(({ id, element }, index) => (
<TabPanel
index={index}
key={id}
className={styles.tabsContent}
data-testid="panel-tabs-content"
>
{id === activeTab.id ? element : null}
</TabPanel>
))
) : (
<EmptyPanelView />
)}
</TabPanels>
</Tabs>
)
})
TabbedPanelContent.displayName = 'TabbedPanelContent'
/**
* Temporary solution to code intel extensions all contributing the same panel actions.
*/
function transformPanelContributions(contributions: Evaluated<Contributions>): Evaluated<Contributions> {
try {
const panelMenuItems = contributions.menus?.['panel/toolbar']
if (!panelMenuItems || panelMenuItems.length === 0) {
return contributions
}
// This won't dedup e.g. [{action: 'a', when: 'b'}, {when: 'b', action: 'a'}], but should
// work for the case this is hackily trying to prevent: multiple extensions generated with the
// same manifest.
const strings = new Set(panelMenuItems.map(menuItem => JSON.stringify(menuItem)))
const uniquePanelMenuItems = [...strings]
.map(string => JSON.parse(string))
// We render the MixPreciseAndSearchBasedReferencesToggle in React now
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
.filter(
(item: any) =>
item.action !== 'mixPreciseAndSearchBasedReferences.toggle' &&
item.action !== 'panel.locations.groupByFile'
)
return {
...contributions,
menus: {
...contributions.menus,
'panel/toolbar': uniquePanelMenuItems,
},
}
} catch {
return contributions
}
}