11"use strict" ;
22
33const traverse = require ( 'babel-traverse' ) . default ;
4+ const estraverse = require ( 'estraverse' ) ;
45const util = require ( "./src/util" ) ;
56const cursor = require ( "./src/doc-builders" ) . cursor ;
67const comments = require ( "./src/comments" ) ;
@@ -51,23 +52,40 @@ function ensureAllCommentsPrinted(astComments) {
5152 } ) ;
5253}
5354
54- function findCursorNode ( ast , cursorOffset ) {
55+ function findCursorNode ( ast , opts ) {
56+ const cursorOffset = opts . cursorOffset ;
5557 let cursorNode ;
56- traverse ( ast , {
57- enter : function ( path ) {
58- const node = path . node ;
59- const start = util . locStart ( node ) ;
60- const end = util . locEnd ( node ) ;
61- if ( start <= cursorOffset && cursorOffset <= end ) {
62- cursorNode = node ;
63- } else {
64- return path . skip ( ) ;
58+ if ( opts . parser === 'babylon' ) {
59+ traverse ( ast , {
60+ enter : function ( path ) {
61+ const node = path . node ;
62+ if ( nodeContainsOffset ( node , cursorOffset ) ) {
63+ cursorNode = node ;
64+ } else {
65+ return path . skip ( ) ;
66+ }
6567 }
66- }
67- } ) ;
68+ } ) ;
69+ } else {
70+ estraverse . traverse ( ast , {
71+ enter : function ( node ) {
72+ if ( nodeContainsOffset ( node , cursorOffset ) ) {
73+ cursorNode = node ;
74+ } else {
75+ return this . skip ( ) ;
76+ }
77+ }
78+ } ) ;
79+ }
6880 return cursorNode ;
6981}
7082
83+ function nodeContainsOffset ( node , offset ) {
84+ const start = util . locStart ( node ) ;
85+ const end = util . locEnd ( node ) ;
86+ return start <= offset && offset <= end ;
87+ }
88+
7189function formatWithCursor ( text , opts ) {
7290 let prefix = "" ;
7391 if ( text . startsWith ( "#!" ) ) {
@@ -84,7 +102,7 @@ function formatWithCursor(text, opts) {
84102 const astComments = attachComments ( text , ast , opts ) ;
85103 let cursorOffset ;
86104 if ( opts . cursorOffset >= 0 ) {
87- const cursorNode = findCursorNode ( ast , opts . cursorOffset ) ;
105+ const cursorNode = findCursorNode ( ast , opts ) ;
88106 if ( cursorNode ) {
89107 cursorOffset = opts . cursorOffset - util . locStart ( cursorNode ) ;
90108 opts . cursorNode = cursorNode ;
0 commit comments