UNPKG

@apollographql/graphql-language-service-utils

Version:

Utilities to support the GraphQL Language Service

50 lines (45 loc) 1.36 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.getASTNodeAtPosition = getASTNodeAtPosition; exports.pointToOffset = pointToOffset; var _Range = require('./Range'); var _graphql = require('graphql'); function getASTNodeAtPosition(query, ast, point) { var offset = pointToOffset(query, point); var nodeContainingPosition = void 0; (0, _graphql.visit)(ast, { enter: function enter(node) { if (node.kind !== 'Name' && // We're usually interested in their parents node.loc && node.loc.start <= offset && offset <= node.loc.end) { nodeContainingPosition = node; } else { return false; } }, leave: function leave(node) { if (node.loc && node.loc.start <= offset && offset <= node.loc.end) { return false; } } }); return nodeContainingPosition; } /** * Copyright (c) Facebook, Inc. * All rights reserved. * * This source code is licensed under the license found in the * LICENSE file in the root directory of this source tree. * * */ function pointToOffset(text, point) { var linesUntilPosition = text.split('\n').slice(0, point.line); return point.character + linesUntilPosition.map(function (line) { return line.length + 1; } // count EOL ).reduce(function (a, b) { return a + b; }, 0); }