/
get-definition-at-position.ts
54 lines (52 loc) · 2.27 KB
/
get-definition-at-position.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
import ts from 'typescript';
import { visit, type FragmentSpreadNode } from 'graphql';
import { getFragmentsInDocument } from '../gql-ast-util';
import type { AnalysisContext, GetDefinitionAtPosition } from './types';
export function getDefinitionAtPosition(
ctx: AnalysisContext,
delegate: GetDefinitionAtPosition,
fileName: string,
position: number,
) {
if (ctx.getScriptSourceHelper().isExcluded(fileName)) return delegate(fileName, position);
const node = ctx.findAscendantTemplateNode(fileName, position);
if (!node) return delegate(fileName, position);
const { resolvedInfo } = ctx.resolveTemplateInfo(fileName, node);
if (!resolvedInfo) return delegate(fileName, position);
const { combinedText, getInnerPosition, getSourcePosition } = resolvedInfo;
const documentNode = ctx.getGraphQLDocumentNode(combinedText);
if (!documentNode) return delegate(fileName, position);
try {
const innerPosition = getInnerPosition(position);
if (innerPosition.isInOtherExpression) return delegate(fileName, position);
let fragmentSpreadNodeUnderCursor: FragmentSpreadNode | undefined = undefined;
visit(documentNode, {
FragmentSpread: node => {
if (node.loc!.start <= innerPosition.pos && innerPosition.pos < node.loc!.end) {
fragmentSpreadNodeUnderCursor = node;
}
},
});
if (!fragmentSpreadNodeUnderCursor) return delegate(fileName, position);
const foundFragmentDefinitionNode = getFragmentsInDocument(documentNode).find(
fragmentDef => fragmentDef.name.value === fragmentSpreadNodeUnderCursor?.name.value,
);
if (!foundFragmentDefinitionNode) return delegate(fileName, position);
const definitionSourcePosition = getSourcePosition(foundFragmentDefinitionNode.name.loc!.start);
return [
{
fileName: definitionSourcePosition.fileName,
name: foundFragmentDefinitionNode.name.value,
textSpan: {
start: definitionSourcePosition.pos,
length: foundFragmentDefinitionNode.name.loc!.end - foundFragmentDefinitionNode.name.loc!.start,
},
kind: ts.ScriptElementKind.unknown,
containerKind: ts.ScriptElementKind.unknown,
containerName: '',
},
] satisfies ts.DefinitionInfo[];
} catch {
return delegate(fileName, position);
}
}