mirror of
https://github.com/usebruno/bruno.git
synced 2026-06-29 23:54:24 +00:00
feat: graphql query syntax highlighting
This commit is contained in:
@@ -4,6 +4,10 @@ const StyledWrapper = styled.div`
|
||||
div.CodeMirror {
|
||||
border: solid 1px #e1e1e1;
|
||||
}
|
||||
|
||||
textarea.cm-editor {
|
||||
position: relative;
|
||||
}
|
||||
`;
|
||||
|
||||
export default StyledWrapper;
|
||||
|
||||
@@ -1,52 +1,218 @@
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
/**
|
||||
* Copyright (c) 2021 GraphQL Contributors.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import CodeMirror from 'codemirror';
|
||||
import MD from 'markdown-it';
|
||||
import StyledWrapper from './StyledWrapper';
|
||||
import * as CodeMirror from 'codemirror';
|
||||
|
||||
const QueryEditor = ({query, onChange, width}) => {
|
||||
const [cmEditor, setCmEditor] = useState(null);
|
||||
const editor = useRef();
|
||||
import onHasCompletion from './onHasCompletion';
|
||||
|
||||
useEffect(() => {
|
||||
if (editor.current && !cmEditor) {
|
||||
const _cmEditor = CodeMirror.fromTextArea(editor.current, {
|
||||
value: '',
|
||||
lineNumbers: true,
|
||||
matchBrackets: true,
|
||||
autoCloseBrackets: true,
|
||||
mode: "graphql",
|
||||
foldGutter: true,
|
||||
gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
|
||||
lineWrapping: true
|
||||
});
|
||||
const md = new MD();
|
||||
const AUTO_COMPLETE_AFTER_KEY = /^[a-zA-Z0-9_@(]$/;
|
||||
|
||||
_cmEditor.setValue(query || 'query { }');
|
||||
export default class QueryEditor extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
|
||||
setCmEditor(_cmEditor);
|
||||
// Keep a cached version of the value, this cache will be updated when the
|
||||
// editor is updated, which can later be used to protect the editor from
|
||||
// unnecessary updates during the update lifecycle.
|
||||
this.cachedValue = props.value || '';
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
const editor = (this.editor = CodeMirror(this._node, {
|
||||
value: this.props.value || '',
|
||||
lineNumbers: true,
|
||||
tabSize: 2,
|
||||
mode: 'graphql',
|
||||
theme: this.props.editorTheme || 'graphiql',
|
||||
keyMap: 'sublime',
|
||||
autoCloseBrackets: true,
|
||||
matchBrackets: true,
|
||||
showCursorWhenSelecting: true,
|
||||
readOnly: this.props.readOnly ? 'nocursor' : false,
|
||||
foldGutter: {
|
||||
minFoldSize: 4,
|
||||
},
|
||||
lint: {
|
||||
schema: this.props.schema,
|
||||
validationRules: this.props.validationRules ?? null,
|
||||
// linting accepts string or FragmentDefinitionNode[]
|
||||
externalFragments: this.props?.externalFragments,
|
||||
},
|
||||
hintOptions: {
|
||||
schema: this.props.schema,
|
||||
closeOnUnfocus: false,
|
||||
completeSingle: false,
|
||||
container: this._node,
|
||||
externalFragments: this.props?.externalFragments,
|
||||
},
|
||||
info: {
|
||||
schema: this.props.schema,
|
||||
renderDescription: (text) => md.render(text),
|
||||
onClick: (reference) =>
|
||||
this.props.onClickReference && this.props.onClickReference(reference),
|
||||
},
|
||||
jump: {
|
||||
schema: this.props.schema,
|
||||
onClick: (reference) =>
|
||||
this.props.onClickReference && this.props.onClickReference(reference)
|
||||
},
|
||||
gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
|
||||
extraKeys: {
|
||||
'Cmd-Space': () =>
|
||||
editor.showHint({ completeSingle: true, container: this._node }),
|
||||
'Ctrl-Space': () =>
|
||||
editor.showHint({ completeSingle: true, container: this._node }),
|
||||
'Alt-Space': () =>
|
||||
editor.showHint({ completeSingle: true, container: this._node }),
|
||||
'Shift-Space': () =>
|
||||
editor.showHint({ completeSingle: true, container: this._node }),
|
||||
'Shift-Alt-Space': () =>
|
||||
editor.showHint({ completeSingle: true, container: this._node }),
|
||||
|
||||
'Cmd-Enter': () => {
|
||||
if (this.props.onRunQuery) {
|
||||
this.props.onRunQuery();
|
||||
}
|
||||
},
|
||||
'Ctrl-Enter': () => {
|
||||
if (this.props.onRunQuery) {
|
||||
this.props.onRunQuery();
|
||||
}
|
||||
},
|
||||
|
||||
'Shift-Ctrl-C': () => {
|
||||
if (this.props.onCopyQuery) {
|
||||
this.props.onCopyQuery();
|
||||
}
|
||||
},
|
||||
|
||||
'Shift-Ctrl-P': () => {
|
||||
if (this.props.onPrettifyQuery) {
|
||||
this.props.onPrettifyQuery();
|
||||
}
|
||||
},
|
||||
|
||||
/* Shift-Ctrl-P is hard coded in Firefox for private browsing so adding an alternative to Pretiffy */
|
||||
|
||||
'Shift-Ctrl-F': () => {
|
||||
if (this.props.onPrettifyQuery) {
|
||||
this.props.onPrettifyQuery();
|
||||
}
|
||||
},
|
||||
|
||||
'Shift-Ctrl-M': () => {
|
||||
if (this.props.onMergeQuery) {
|
||||
this.props.onMergeQuery();
|
||||
}
|
||||
},
|
||||
'Cmd-S': () => {
|
||||
if (this.props.onRunQuery) {
|
||||
// empty
|
||||
}
|
||||
},
|
||||
|
||||
'Ctrl-S': () => {
|
||||
if (this.props.onRunQuery) {
|
||||
// empty
|
||||
}
|
||||
},
|
||||
},
|
||||
}));
|
||||
if (editor) {
|
||||
editor.on('change', this._onEdit);
|
||||
editor.on('keyup', this._onKeyUp);
|
||||
editor.on('hasCompletion', this._onHasCompletion);
|
||||
editor.on('beforeChange', this._onBeforeChange);
|
||||
}
|
||||
}
|
||||
|
||||
return () => {
|
||||
if(cmEditor) {
|
||||
cmEditor.toTextArea();
|
||||
componentDidUpdate(prevProps) {
|
||||
// Ensure the changes caused by this update are not interpretted as
|
||||
// user-input changes which could otherwise result in an infinite
|
||||
// event loop.
|
||||
this.ignoreChangeEvent = true;
|
||||
if (this.props.schema !== prevProps.schema && this.editor) {
|
||||
this.editor.options.lint.schema = this.props.schema;
|
||||
this.editor.options.hintOptions.schema = this.props.schema;
|
||||
this.editor.options.info.schema = this.props.schema;
|
||||
this.editor.options.jump.schema = this.props.schema;
|
||||
CodeMirror.signal(this.editor, 'change', this.editor);
|
||||
}
|
||||
if (
|
||||
this.props.value !== prevProps.value &&
|
||||
this.props.value !== this.cachedValue &&
|
||||
this.editor
|
||||
) {
|
||||
this.cachedValue = this.props.value;
|
||||
this.editor.setValue(this.props.value);
|
||||
}
|
||||
this.ignoreChangeEvent = false;
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
if (this.editor) {
|
||||
this.editor.off('change', this._onEdit);
|
||||
this.editor.off('keyup', this._onKeyUp);
|
||||
this.editor.off('hasCompletion', this._onHasCompletion);
|
||||
this.editor = null;
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<StyledWrapper
|
||||
className="mt-4"
|
||||
aria-label="Query Editor"
|
||||
ref={node => {
|
||||
this._node = node;
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Public API for retrieving the DOM client height for this component.
|
||||
*/
|
||||
getClientHeight() {
|
||||
return this._node && this._node.clientHeight;
|
||||
}
|
||||
|
||||
_onKeyUp = (_cm, event) => {
|
||||
if (AUTO_COMPLETE_AFTER_KEY.test(event.key) && this.editor) {
|
||||
this.editor.execCommand('autocomplete');
|
||||
}
|
||||
};
|
||||
|
||||
_onEdit = () => {
|
||||
if (!this.ignoreChangeEvent && this.editor) {
|
||||
this.cachedValue = this.editor.getValue();
|
||||
if (this.props.onEdit) {
|
||||
this.props.onEdit(this.cachedValue);
|
||||
}
|
||||
}
|
||||
}, [editor.current, cmEditor]);
|
||||
};
|
||||
|
||||
return (
|
||||
<StyledWrapper>
|
||||
<div className="mt-4">
|
||||
<textarea
|
||||
id="operation"
|
||||
style={{
|
||||
width: `${width}px`,
|
||||
height: '400px'
|
||||
}}
|
||||
ref={editor}
|
||||
className="cm-editor"
|
||||
>
|
||||
</textarea>
|
||||
</div>
|
||||
</StyledWrapper>
|
||||
);
|
||||
};
|
||||
/**
|
||||
* Render a custom UI for CodeMirror's hint which includes additional info
|
||||
* about the type and description for the selected context.
|
||||
*/
|
||||
_onHasCompletion = (cm, data) => {
|
||||
onHasCompletion(cm, data, this.props.onHintInformationRender);
|
||||
};
|
||||
|
||||
export default QueryEditor;
|
||||
_onBeforeChange(_instance, change) {
|
||||
// The update function is only present on non-redo, non-undo events.
|
||||
if (change.origin === 'paste') {
|
||||
const text = change.text.map(normalizeWhitespace);
|
||||
change.update(change.from, change.to, text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* Copyright (c) 2021 GraphQL Contributors.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
import escapeHTML from 'escape-html';
|
||||
import MD from 'markdown-it';
|
||||
|
||||
import {
|
||||
GraphQLNonNull,
|
||||
GraphQLList,
|
||||
GraphQLType,
|
||||
GraphQLField,
|
||||
} from 'graphql';
|
||||
|
||||
const md = new MD();
|
||||
|
||||
/**
|
||||
* Render a custom UI for CodeMirror's hint which includes additional info
|
||||
* about the type and description for the selected context.
|
||||
*/
|
||||
export default function onHasCompletion(
|
||||
_cm,
|
||||
data,
|
||||
onHintInformationRender,
|
||||
) {
|
||||
const CodeMirror = require('codemirror');
|
||||
|
||||
let information;
|
||||
let deprecation;
|
||||
|
||||
// When a hint result is selected, we augment the UI with information.
|
||||
CodeMirror.on(
|
||||
data,
|
||||
'select',
|
||||
(ctx, el) => {
|
||||
// Only the first time (usually when the hint UI is first displayed)
|
||||
// do we create the information nodes.
|
||||
if (!information) {
|
||||
const hintsUl = el.parentNode;
|
||||
|
||||
// This "information" node will contain the additional info about the
|
||||
// highlighted typeahead option.
|
||||
information = document.createElement('div');
|
||||
information.className = 'CodeMirror-hint-information';
|
||||
hintsUl.appendChild(information);
|
||||
|
||||
// This "deprecation" node will contain info about deprecated usage.
|
||||
deprecation = document.createElement('div');
|
||||
deprecation.className = 'CodeMirror-hint-deprecation';
|
||||
hintsUl.appendChild(deprecation);
|
||||
|
||||
// When CodeMirror attempts to remove the hint UI, we detect that it was
|
||||
// removed and in turn remove the information nodes.
|
||||
let onRemoveFn;
|
||||
hintsUl.addEventListener(
|
||||
'DOMNodeRemoved',
|
||||
(onRemoveFn = (event) => {
|
||||
if (event.target === hintsUl) {
|
||||
hintsUl.removeEventListener('DOMNodeRemoved', onRemoveFn);
|
||||
information = null;
|
||||
deprecation = null;
|
||||
onRemoveFn = null;
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// Now that the UI has been set up, add info to information.
|
||||
const description = ctx.description
|
||||
? md.render(ctx.description)
|
||||
: 'Self descriptive.';
|
||||
const type = ctx.type
|
||||
? '<span class="infoType">' + renderType(ctx.type) + '</span>'
|
||||
: '';
|
||||
|
||||
information.innerHTML =
|
||||
'<div class="content">' +
|
||||
(description.slice(0, 3) === '<p>'
|
||||
? '<p>' + type + description.slice(3)
|
||||
: type + description) +
|
||||
'</div>';
|
||||
|
||||
if (ctx && deprecation && ctx.deprecationReason) {
|
||||
const reason = ctx.deprecationReason
|
||||
? md.render(ctx.deprecationReason)
|
||||
: '';
|
||||
deprecation.innerHTML =
|
||||
'<span class="deprecation-label">Deprecated</span>' + reason;
|
||||
deprecation.style.display = 'block';
|
||||
} else if (deprecation) {
|
||||
deprecation.style.display = 'none';
|
||||
}
|
||||
|
||||
// Additional rendering?
|
||||
if (onHintInformationRender) {
|
||||
onHintInformationRender(information);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function renderType(type) {
|
||||
if (type instanceof GraphQLNonNull) {
|
||||
return `${renderType(type.ofType)}!`;
|
||||
}
|
||||
if (type instanceof GraphQLList) {
|
||||
return `[${renderType(type.ofType)}]`;
|
||||
}
|
||||
return `<a class="typeName">${escapeHTML(type.name)}</a>`;
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { Tab, TabList, TabPanel, Tabs } from 'react-tabs';
|
||||
import StyledWrapper from './StyledWrapper';
|
||||
import QueryEditor from '../QueryEditor';
|
||||
|
||||
const RequestPane = ({leftPaneWidth, query, onQueryChange}) => {
|
||||
const RequestPane = ({onRunQuery, schema, leftPaneWidth, value, onQueryChange}) => {
|
||||
return (
|
||||
<StyledWrapper className="">
|
||||
<Tabs className='react-tabs mt-1 flex flex-grow flex-col' forceRenderTabPanel>
|
||||
@@ -13,8 +13,10 @@ const RequestPane = ({leftPaneWidth, query, onQueryChange}) => {
|
||||
</TabList>
|
||||
<TabPanel>
|
||||
<QueryEditor
|
||||
schema={schema}
|
||||
width={leftPaneWidth}
|
||||
query={query}
|
||||
value={value}
|
||||
onRunQuery={onRunQuery}
|
||||
onChange={onQueryChange}
|
||||
/>
|
||||
</TabPanel>
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
flattenItems,
|
||||
findItem
|
||||
} from '../../utils';
|
||||
import useGraphqlSchema from '../../hooks/useGraphqlSchema';
|
||||
|
||||
import StyledWrapper from './StyledWrapper';
|
||||
|
||||
@@ -19,6 +20,9 @@ const RequestTabPanel = ({collections, activeRequestTabId, requestTabs}) => {
|
||||
let asideWidth = 200;
|
||||
let [data, setData] = useState({});
|
||||
let [url, setUrl] = useState('https://api.spacex.land/graphql');
|
||||
let {
|
||||
schema
|
||||
} = useGraphqlSchema('https://api.spacex.land/graphql');
|
||||
let [query, setQuery] = useState('');
|
||||
let [isLoading, setIsLoading] = useState(false);
|
||||
const [leftPaneWidth, setLeftPaneWidth] = useState(500);
|
||||
@@ -49,12 +53,8 @@ const RequestTabPanel = ({collections, activeRequestTabId, requestTabs}) => {
|
||||
};
|
||||
}, [dragging, leftPaneWidth]);
|
||||
|
||||
const onUrlChange = (value) => {
|
||||
setUrl(value);
|
||||
};
|
||||
const onQueryChange = (value) => {
|
||||
setQuery(value);
|
||||
};
|
||||
const onUrlChange = (value) => setUrl(value);
|
||||
const onQueryChange = (value) => setQuery(value);
|
||||
|
||||
if(!activeRequestTabId) {
|
||||
return (
|
||||
@@ -116,8 +116,10 @@ const RequestTabPanel = ({collections, activeRequestTabId, requestTabs}) => {
|
||||
<section className="request-pane px-4">
|
||||
<div style={{width: `${leftPaneWidth}px`}}>
|
||||
<RequestPane
|
||||
onRunQuery={runQuery}
|
||||
schema={schema}
|
||||
leftPaneWidth={leftPaneWidth}
|
||||
query={item.request.body.graphql.query}
|
||||
value={item.request.body.graphql.query}
|
||||
onQueryChange={onQueryChange}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { getIntrospectionQuery, buildClientSchema } from 'graphql';
|
||||
|
||||
const useGraphqlSchema =(endpoint) => {
|
||||
const [isLoaded, setIsLoaded] = useState(false);
|
||||
const [schema, setSchema] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const introspectionQuery = getIntrospectionQuery();
|
||||
const queryParams = {
|
||||
query: introspectionQuery
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
fetch(endpoint, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(queryParams)
|
||||
})
|
||||
.then((res) => res.json())
|
||||
.then((s) => {
|
||||
if(s && s.data) {
|
||||
setSchema(buildClientSchema(s.data));
|
||||
setIsLoaded(true);
|
||||
} else {
|
||||
return Promise.reject(new Error('An error occurred while introspecting schema'));
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
setError(err);
|
||||
console.log(err);
|
||||
});
|
||||
}, []);
|
||||
|
||||
return {
|
||||
isLoaded,
|
||||
schema,
|
||||
error
|
||||
};
|
||||
}
|
||||
|
||||
export default useGraphqlSchema;
|
||||
Reference in New Issue
Block a user