From 55e428bbe379c22cc9a45a89af63887ea307b8eb Mon Sep 17 00:00:00 2001 From: Mike Ellan <52717970+sonicyeti@users.noreply.github.com> Date: Thu, 6 Aug 2020 14:39:37 -0400 Subject: [PATCH] Checking format to offset line number if spec string is JSON parsable. (#2467) * Checking format to offset line number if spec string is JSON parsable. * Cleaning up server component detection, removing unused function --- .../spec-editor/spec-editor-sidebar.js | 33 ++++++++++++++----- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/packages/insomnia-app/app/ui/components/spec-editor/spec-editor-sidebar.js b/packages/insomnia-app/app/ui/components/spec-editor/spec-editor-sidebar.js index 158641d88..463499ff7 100644 --- a/packages/insomnia-app/app/ui/components/spec-editor/spec-editor-sidebar.js +++ b/packages/insomnia-app/app/ui/components/spec-editor/spec-editor-sidebar.js @@ -28,6 +28,7 @@ class SpecEditorSidebar extends React.Component { super(props); this.state = { error: '', + specContentJSON: false, }; } @@ -45,11 +46,7 @@ class SpecEditorSidebar extends React.Component { _mapPosition(itemPath: Array) { const sourceMap = new YAMLSourceMap(); - const specMap = sourceMap.index( - YAML.parseDocument(this.props.apiSpec.contents, { keepCstNodes: true }), - ); - const itemMappedPosition = sourceMap.lookup(itemPath, specMap); - const isServersSection = itemPath[0] === 'servers'; + const { contents } = this.props.apiSpec; const scrollPosition = { start: { line: 0, @@ -60,10 +57,19 @@ class SpecEditorSidebar extends React.Component { col: 200, }, }; - isServersSection - ? (scrollPosition.start.line = itemMappedPosition.start.line) - : (scrollPosition.start.line = itemMappedPosition.start.line - 1); + // Account for JSON (as string) line number shift + if (this.state.specContentJSON) { + scrollPosition.start.line = 1; + } + const specMap = sourceMap.index(YAML.parseDocument(contents, { keepCstNodes: true })); + const itemMappedPosition = sourceMap.lookup(itemPath, specMap); + const isServersSection = itemPath[0] === 'servers'; + scrollPosition.start.line += itemMappedPosition.start.line; + if (!isServersSection) { + scrollPosition.start.line -= 1; + } scrollPosition.end.line = scrollPosition.start.line; + this._handleScrollEditor(scrollPosition); } @@ -71,6 +77,17 @@ class SpecEditorSidebar extends React.Component { this._mapPosition(itemPath); }; + componentDidMount() { + const { contents } = this.props.apiSpec; + try { + JSON.parse(contents); + } catch (e) { + this.setState({ specContentJSON: false }); + return; + } + this.setState({ specContentJSON: true }); + } + render() { const { error } = this.state; if (error) {