1 | import { visit } from 'graphql';
|
2 | export function getASTNodeAtPosition(query, ast, point) {
|
3 | const offset = pointToOffset(query, point);
|
4 | let nodeContainingPosition;
|
5 | visit(ast, {
|
6 | enter(node) {
|
7 | if (node.kind !== 'Name' &&
|
8 | node.loc &&
|
9 | node.loc.start <= offset &&
|
10 | offset <= node.loc.end) {
|
11 | nodeContainingPosition = node;
|
12 | }
|
13 | else {
|
14 | return false;
|
15 | }
|
16 | },
|
17 | leave(node) {
|
18 | if (node.loc && node.loc.start <= offset && offset <= node.loc.end) {
|
19 | return false;
|
20 | }
|
21 | },
|
22 | });
|
23 | return nodeContainingPosition;
|
24 | }
|
25 | export function pointToOffset(text, point) {
|
26 | const linesUntilPosition = text.split('\n').slice(0, point.line);
|
27 | return (point.character +
|
28 | linesUntilPosition
|
29 | .map(line => line.length + 1)
|
30 | .reduce((a, b) => a + b, 0));
|
31 | }
|
32 |
|
\ | No newline at end of file |