/
actions.ts
399 lines (380 loc) · 17.7 KB
/
actions.ts
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
import { HoveredToken, LOADER_DELAY } from '@sourcegraph/codeintellify'
import * as H from 'history'
import { isEqual, uniqWith } from 'lodash'
import { combineLatest, merge, Observable, of, Subscription, Unsubscribable } from 'rxjs'
import {
catchError,
delay,
distinctUntilChanged,
filter,
first,
map,
share,
startWith,
switchMap,
takeUntil,
} from 'rxjs/operators'
import { ActionItemAction } from '../actions/ActionItem'
import { Context } from '../api/client/context/context'
import { parse, parseTemplate } from '../api/client/context/expr/evaluator'
import { Services } from '../api/client/services'
import { WorkspaceRootWithMetadata } from '../api/client/services/workspaceService'
import { ContributableMenu, TextDocumentPositionParams } from '../api/protocol'
import { ERPRIVATEREPOPUBLICSOURCEGRAPHCOM } from '../backend/errors'
import { resolveRawRepoName } from '../backend/repo'
import { getContributedActionItems } from '../contributions/contributions'
import { ExtensionsControllerProps } from '../extensions/controller'
import { PlatformContext, PlatformContextProps } from '../platform/context'
import { asError, ErrorLike, isErrorLike } from '../util/errors'
import { makeRepoURI, parseRepoURI, withWorkspaceRootInputRevision } from '../util/url'
import { HoverContext } from './HoverOverlay'
const LOADING: 'loading' = 'loading'
/**
* This function is passed to {@link module:@sourcegraph/codeintellify.createHoverifier}, which uses it to fetch
* the list of buttons to display on the hover tooltip. This function in turn determines that by looking at all
* action contributions for the "hover" menu. It also defines two builtin hover actions: "Go to definition" and
* "Find references".
*/
export function getHoverActions(
{
extensionsController,
platformContext,
}: ExtensionsControllerProps & PlatformContextProps<'urlToFile' | 'requestGraphQL'>,
hoverContext: HoveredToken & HoverContext
): Observable<ActionItemAction[]> {
return getHoverActionsContext({ extensionsController, platformContext }, hoverContext).pipe(
switchMap(context =>
extensionsController.services.contribution
.getContributions(undefined, context)
.pipe(map(contributions => getContributedActionItems(contributions, ContributableMenu.Hover)))
)
)
}
/**
* The scoped context properties for the hover.
*
* @internal Exported for testing only.
*/
export interface HoverActionsContext extends Context<TextDocumentPositionParams> {
['goToDefinition.showLoading']: boolean
['goToDefinition.url']: string | null
['goToDefinition.notFound']: boolean
['goToDefinition.error']: boolean
['findReferences.url']: string | null
hoverPosition: TextDocumentPositionParams
}
/**
* Returns an observable that emits the scoped context for the hover upon subscription and whenever it changes.
*
* @internal Exported for testing only.
*/
export function getHoverActionsContext(
{
extensionsController,
platformContext: { urlToFile, requestGraphQL },
}:
| (ExtensionsControllerProps & PlatformContextProps<'urlToFile' | 'requestGraphQL'>)
| {
extensionsController: {
services: {
workspace: {
roots: { value: readonly WorkspaceRootWithMetadata[] }
}
textDocumentDefinition: Pick<Services['textDocumentDefinition'], 'getLocations'>
textDocumentReferences: Pick<Services['textDocumentReferences'], 'providersForDocument'>
}
}
platformContext: Pick<PlatformContext, 'urlToFile' | 'requestGraphQL'>
},
hoverContext: HoveredToken & HoverContext
): Observable<Context<TextDocumentPositionParams>> {
const params: TextDocumentPositionParams = {
textDocument: { uri: makeRepoURI(hoverContext) },
position: { line: hoverContext.line - 1, character: hoverContext.character - 1 },
}
const definitionURLOrError = getDefinitionURL(
{ urlToFile, requestGraphQL },
extensionsController.services,
params
).pipe(
map(result => (result ? result.url : result)), // we only care about the URL or null, not whether there are multiple
catchError(err => [asError(err) as ErrorLike]),
share()
)
return combineLatest([
// the fairly long LOADER_DELAY has elapsed.
merge(
[undefined], // don't block on the first emission
of(LOADING).pipe(delay(LOADER_DELAY), takeUntil(definitionURLOrError)),
definitionURLOrError
),
// Only show "Find references" if a reference provider is registered. Unlike definitions, references are
// not preloaded and here just involve statically constructing a URL, so no need to indicate loading.
extensionsController.services.textDocumentReferences
.providersForDocument(params.textDocument)
.pipe(map(providers => providers.length !== 0)),
// If there is no definition, delay showing "Find references" because it is likely that the token is
// punctuation or something else that has no meaningful references. This reduces UI jitter when it can be
// quickly determined that there is no definition. TODO(sqs): Allow reference providers to register
// "trigger characters" or have a "hasReferences" method to opt-out of being called for certain tokens.
merge(
of(true).pipe(delay(LOADER_DELAY), takeUntil(definitionURLOrError.pipe(filter(v => !!v)))),
definitionURLOrError.pipe(
filter(v => !!v),
map(v => !!v)
)
).pipe(startWith(false)),
]).pipe(
map(
([definitionURLOrError, hasReferenceProvider, showFindReferences]): HoverActionsContext => ({
'goToDefinition.showLoading': definitionURLOrError === LOADING,
'goToDefinition.url':
(definitionURLOrError !== LOADING && !isErrorLike(definitionURLOrError) && definitionURLOrError) ||
null,
'goToDefinition.notFound':
definitionURLOrError !== LOADING &&
!isErrorLike(definitionURLOrError) &&
definitionURLOrError === null,
'goToDefinition.error': isErrorLike(definitionURLOrError) && (definitionURLOrError as any).stack,
'findReferences.url':
hasReferenceProvider && showFindReferences
? urlToFile({ ...hoverContext, position: hoverContext, viewState: 'references' })
: null,
// Store hoverPosition for the goToDefinition action's commandArguments to refer to.
hoverPosition: params,
})
),
distinctUntilChanged((a, b) => isEqual(a, b))
)
}
/**
* Returns an observable that emits null if no definitions are found, {url, multiple: false} if exactly 1
* definition is found, {url: defPanelURL, multiple: true} if multiple definitions are found, or an error.
*
* @internal Exported for testing only.
*/
export function getDefinitionURL(
{ urlToFile, requestGraphQL }: Pick<PlatformContext, 'urlToFile' | 'requestGraphQL'>,
{
workspace,
textDocumentDefinition,
}: {
workspace: {
roots: { value: readonly WorkspaceRootWithMetadata[] }
}
textDocumentDefinition: Pick<Services['textDocumentDefinition'], 'getLocations'>
},
params: TextDocumentPositionParams
): Observable<{ url: string; multiple: boolean } | null> {
return textDocumentDefinition.getLocations(params).pipe(
switchMap(locations => locations),
switchMap(definitions => {
if (definitions === null || definitions.length === 0) {
return of(null)
}
// Get unique definitions.
definitions = uniqWith(definitions, isEqual)
if (definitions.length > 1) {
// Open the panel to show all definitions.
const uri = withWorkspaceRootInputRevision(
workspace.roots.value || [],
parseRepoURI(params.textDocument.uri)
)
return of({
url: urlToFile({
...uri,
rev: uri.rev || '',
filePath: uri.filePath || '',
position: { line: params.position.line + 1, character: params.position.character + 1 },
viewState: 'def',
}),
multiple: true,
})
}
const def = definitions[0]
// Preserve the input revision (e.g., a Git branch name instead of a Git commit SHA) if the result is
// inside one of the current roots. This avoids navigating the user from (e.g.) a URL with a nice Git
// branch name to a URL with a full Git commit SHA.
const uri = withWorkspaceRootInputRevision(workspace.roots.value || [], parseRepoURI(def.uri))
if (def.range) {
uri.position = {
line: def.range.start.line + 1,
character: def.range.start.character + 1,
}
}
// When returning a single definition, include the repo's
// `rawRepoName`, to allow building URLs on the code host.
return resolveRawRepoName({ ...uri, requestGraphQL }).pipe(
// When encountering an ERPRIVATEREPOPUBLICSOURCEGRAPHCOM, we can assume that
// we're executing in a browser extension pointed to the public sourcegraph.com,
// in which case repoName === rawRepoName.
catchError(err => {
if (isErrorLike(err) && err.code === ERPRIVATEREPOPUBLICSOURCEGRAPHCOM) {
return [uri.repoName]
}
throw err
}),
map(rawRepoName => ({
url: urlToFile({
...uri,
rev: uri.rev || '',
filePath: uri.filePath || '',
rawRepoName,
}),
multiple: false,
}))
)
})
)
}
/**
* Registers contributions for hover-related functionality.
*/
export function registerHoverContributions({
extensionsController,
platformContext: { urlToFile, requestGraphQL },
history,
}: (
| (ExtensionsControllerProps & PlatformContextProps)
| {
extensionsController: {
services: Pick<Services, 'commands' | 'contribution'> & {
workspace: {
roots: { value: readonly WorkspaceRootWithMetadata[] }
}
textDocumentDefinition: Pick<Services['textDocumentDefinition'], 'getLocations'>
}
}
platformContext: Pick<PlatformContext, 'urlToFile' | 'requestGraphQL'>
}
) & {
history: H.History
}): Unsubscribable {
const subscriptions = new Subscription()
// Registers the "Go to definition" action shown in the hover tooltip. When clicked, the action finds the
// definition of the token using the registered definition providers and navigates the user there.
//
// When the user hovers over a token (even before they click "Go to definition"), it attempts to preload the
// definition. If preloading succeeds and at least 1 definition is found, the "Go to definition" action becomes
// a normal link (<a href>) pointing to the definition's URL. Using a normal link here is good for a11y and UX
// (e.g., open-in-new-tab works and the browser status bar shows the URL).
//
// Otherwise (if preloading fails, or if preloading has not yet finished), clicking "Go to definition" executes
// the goToDefinition command. A loading indicator is displayed, and any errors that occur during execution are
// shown to the user.
//
// Future improvements:
//
// TODO(sqs): If the user middle-clicked or Cmd/Ctrl-clicked the button, it would be nice if when the
// definition was found, a new browser tab was opened to the destination. This is not easy because browsers
// usually block new tabs opened by JavaScript not directly triggered by a user mouse/keyboard interaction.
//
// TODO(sqs): Pin hover after an action has been clicked and before it has completed.
subscriptions.add(
extensionsController.services.contribution.registerContributions({
contributions: {
actions: [
{
id: 'goToDefinition',
title: parseTemplate('Go to definition'),
command: 'goToDefinition',
commandArguments: [
/* eslint-disable no-template-curly-in-string */
parseTemplate('${json(hoverPosition)}'),
/* eslint-enable no-template-curly-in-string */
],
},
{
// This action is used when preloading the definition succeeded and at least 1
// definition was found.
id: 'goToDefinition.preloaded',
title: parseTemplate('Go to definition'),
command: 'open',
// eslint-disable-next-line no-template-curly-in-string
commandArguments: [parseTemplate('${goToDefinition.url}')],
},
],
menus: {
hover: [
// Do not show any actions if no definition provider is registered. (In that case,
// goToDefinition.{error, loading, url} will all be falsey.)
{
action: 'goToDefinition',
when: parse('goToDefinition.error || goToDefinition.showLoading'),
},
{
action: 'goToDefinition.preloaded',
when: parse('goToDefinition.url'),
},
],
},
},
})
)
subscriptions.add(
extensionsController.services.commands.registerCommand({
command: 'goToDefinition',
run: async (paramsStr: string) => {
const params: TextDocumentPositionParams = JSON.parse(paramsStr)
const result = await getDefinitionURL(
{ urlToFile, requestGraphQL },
extensionsController.services,
params
)
.pipe(first())
.toPromise()
if (!result) {
throw new Error('No definition found.')
}
if (result.url === H.createPath(history.location)) {
// The user might be confused if they click "Go to definition" and don't go anywhere, which
// occurs if they are *already* on the definition. Give a helpful tip if they do this.
//
// Note that these tips won't show up if the definition URL is already known by the time they
// click "Go to definition", because then it's a normal link and not a button that executes
// this command. TODO: It would be nice if they also showed up in that case.
if (result.multiple) {
// The user may not have noticed the panel at the bottom of the screen, so tell them
// explicitly.
throw new Error('Multiple definitions shown in panel below.')
}
throw new Error('Already at the definition.')
}
history.push(result.url)
},
})
)
// Register the "Find references" action shown in the hover tooltip. This is simpler than "Go to definition"
// because it just needs a URL that can be statically constructed from the current URL (it does not need to
// query any providers).
subscriptions.add(
extensionsController.services.contribution.registerContributions({
contributions: {
actions: [
{
id: 'findReferences',
title: parseTemplate('Find references'),
command: 'open',
// eslint-disable-next-line no-template-curly-in-string
commandArguments: [parseTemplate('${findReferences.url}')],
},
],
menus: {
hover: [
// To reduce UI jitter, even though "Find references" can be shown immediately (because
// the URL can be statically constructed), don't show it until either (1) "Go to
// definition" is showing or (2) the LOADER_DELAY has elapsed. The part (2) of this
// logic is implemented in the observable pipe that sets findReferences.url above.
{
action: 'findReferences',
when: parse(
'findReferences.url && (goToDefinition.showLoading || goToDefinition.url || goToDefinition.error)'
),
},
],
},
},
})
)
return subscriptions
}