forked from lifeart/els-addon-glint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
77 lines (67 loc) · 2.19 KB
/
index.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
import * as t from '@babel/types';
import * as fs from 'fs';
import {
AddonAPI,
DefinitionFunctionParams,
} from '@lifeart/ember-language-server';
import { Location, Range } from 'vscode-languageserver/node';
import { URI } from 'vscode-uri';
import ASTPath from '@lifeart/ember-language-server/lib/glimmer-utils';
function getImportSpecifierName(
importDeclaration: t.ImportDeclaration,
position: any
) {
const importNameData = importDeclaration.specifiers.find((item) => {
const importLine = item.loc?.start.line;
const importStartCol = item.loc?.start.column;
const importStartEnd = item.loc?.end.column;
return (
importStartCol &&
importStartEnd &&
position.line + 1 === importLine &&
importStartCol <= position.character &&
importStartEnd >= position.character
);
}) as t.ImportSpecifier;
return importNameData && importNameData.type === 'ImportSpecifier'
? (importNameData.imported as t.Identifier).name
: '';
}
function pathsToLocations(paths: Location[], importName?: string): Location[] {
return paths.map((modulePath) => {
const uriPath = modulePath.uri;
const file = fs.readFileSync(URI.parse(uriPath).path, 'utf8');
const arr = file.split(/\r?\n/);
const idxFound = arr.findIndex(
(line) => line.includes(importName) && line.includes('export')
);
return Location.create(
modulePath.uri,
Range.create(idxFound, 0, idxFound, 0)
);
});
}
function hasNodeType(node: any, type: string) {
if (!node) {
return false;
}
return node.type === type;
}
function isImportSpecifier(path: ASTPath): boolean {
return hasNodeType(path.parent, 'ImportSpecifier');
}
module.exports = class ElsAddonImportDefinition implements AddonAPI {
async onDefinition(_: string, params: DefinitionFunctionParams) {
const results = params.results;
if (isImportSpecifier(params.focusPath)) {
const importDec = (params.focusPath.parentFromLevel(
2
) as unknown) as t.ImportDeclaration;
const importName = getImportSpecifierName(importDec, params.position);
if (importName) {
return pathsToLocations(params.results, importName);
}
}
return [...results];
}
};