-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathGraphiQL.tsx
1653 lines (1492 loc) · 47.9 KB
/
GraphiQL.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) 2020 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, {
ComponentType,
PropsWithChildren,
MouseEventHandler,
Component,
FunctionComponent,
} from 'react';
import {
buildClientSchema,
GraphQLSchema,
parse,
print,
OperationDefinitionNode,
IntrospectionQuery,
GraphQLType,
} from 'graphql';
import copyToClipboard from 'copy-to-clipboard';
import { ExecuteButton } from './ExecuteButton';
import { ImagePreview } from './ImagePreview';
import { ToolbarButton } from './ToolbarButton';
import { ToolbarGroup } from './ToolbarGroup';
import { ToolbarMenu, ToolbarMenuItem } from './ToolbarMenu';
import { QueryEditor } from './QueryEditor';
import { VariableEditor } from './VariableEditor';
import { HeaderEditor } from './HeaderEditor';
import { ResultViewer } from './ResultViewer';
import { DocExplorer } from './DocExplorer';
import { QueryHistory } from './QueryHistory';
import CodeMirrorSizer from '../utility/CodeMirrorSizer';
import StorageAPI, { Storage } from '../utility/StorageAPI';
import getQueryFacts, { VariableToType } from '../utility/getQueryFacts';
import getSelectedOperationName from '../utility/getSelectedOperationName';
import debounce from '../utility/debounce';
import find from '../utility/find';
import { GetDefaultFieldNamesFn, fillLeafs } from '../utility/fillLeafs';
import { getLeft, getTop } from '../utility/elementPosition';
import mergeAST from '../utility/mergeAst';
import {
introspectionQuery,
introspectionQueryName,
introspectionQuerySansSubscriptions,
} from '../utility/introspectionQueries';
const DEFAULT_DOC_EXPLORER_WIDTH = 350;
const majorVersion = parseInt(React.version.slice(0, 2), 10);
if (majorVersion < 16) {
throw Error(
[
'GraphiQL 0.18.0 and after is not compatible with React 15 or below.',
'If you are using a CDN source (jsdelivr, unpkg, etc), follow this example:',
'https://github.com/graphql/graphiql/blob/master/examples/graphiql-cdn/index.html#L49',
].join('\n'),
);
}
declare namespace global {
export let g: GraphiQL;
}
export type Maybe<T> = T | null | undefined;
export type FetcherParams = {
query: string;
operationName: string;
variables?: string;
};
export type FetcherOpts = {
headers?: { [key: string]: any };
shouldPersistHeaders: boolean;
};
export type FetcherResult =
| {
data: IntrospectionQuery;
}
| string
| { data: any };
export type Fetcher = (
graphQLParams: FetcherParams,
opts?: FetcherOpts,
) => Promise<FetcherResult> | Observable<FetcherResult>;
type OnMouseMoveFn = Maybe<
(moveEvent: MouseEvent | React.MouseEvent<Element>) => void
>;
type OnMouseUpFn = Maybe<() => void>;
export type GraphiQLProps = {
fetcher: Fetcher;
schema?: GraphQLSchema;
query?: string;
variables?: string;
headers?: string;
operationName?: string;
response?: string;
storage?: Storage;
defaultQuery?: string;
defaultVariableEditorOpen?: boolean;
defaultSecondaryEditorOpen?: boolean;
headerEditorEnabled?: boolean;
shouldPersistHeaders?: boolean;
onCopyQuery?: (query?: string) => void;
onEditQuery?: (query?: string) => void;
onEditVariables?: (value: string) => void;
onEditHeaders?: (value: string) => void;
onEditOperationName?: (operationName: string) => void;
onToggleDocs?: (docExplorerOpen: boolean) => void;
getDefaultFieldNames?: GetDefaultFieldNamesFn;
editorTheme?: string;
onToggleHistory?: (historyPaneOpen: boolean) => void;
ResultsTooltip?: typeof Component | FunctionComponent;
readOnly?: boolean;
docExplorerOpen?: boolean;
};
export type GraphiQLState = {
schema?: GraphQLSchema;
query?: string;
variables?: string;
headers?: string;
operationName?: string;
docExplorerOpen: boolean;
response?: string;
editorFlex: number;
secondaryEditorOpen: boolean;
secondaryEditorHeight: number;
variableEditorActive: boolean;
headerEditorActive: boolean;
headerEditorEnabled: boolean;
shouldPersistHeaders: boolean;
historyPaneOpen: boolean;
docExplorerWidth: number;
isWaitingForResponse: boolean;
subscription?: Unsubscribable | null;
variableToType?: VariableToType;
operations?: OperationDefinitionNode[];
};
/**
* The top-level React component for GraphiQL, intended to encompass the entire
* browser viewport.
*
* @see https://github.com/graphql/graphiql#usage
*/
export class GraphiQL extends React.Component<GraphiQLProps, GraphiQLState> {
/**
* Static Methods
*/
static formatResult(result: any) {
return JSON.stringify(result, null, 2);
}
static formatError(rawError: Error) {
const result = Array.isArray(rawError)
? rawError.map(formatSingleError)
: formatSingleError(rawError);
return JSON.stringify(result, null, 2);
}
// Ensure only the last executed editor query is rendered.
_editorQueryID = 0;
_storage: StorageAPI;
codeMirrorSizer!: CodeMirrorSizer;
// Ensure the component is mounted to execute async setState
componentIsMounted: boolean;
// refs
docExplorerComponent: Maybe<DocExplorer>;
graphiqlContainer: Maybe<HTMLDivElement>;
resultComponent: Maybe<ResultViewer>;
variableEditorComponent: Maybe<VariableEditor>;
headerEditorComponent: Maybe<HeaderEditor>;
_queryHistory: Maybe<QueryHistory>;
editorBarComponent: Maybe<HTMLDivElement>;
queryEditorComponent: Maybe<QueryEditor>;
resultViewerElement: Maybe<HTMLElement>;
constructor(props: GraphiQLProps) {
super(props);
// Ensure props are correct
if (typeof props.fetcher !== 'function') {
throw new TypeError('GraphiQL requires a fetcher function.');
}
// Cache the storage instance
this._storage = new StorageAPI(props.storage);
// Disable setState when the component is not mounted
this.componentIsMounted = false;
// Determine the initial query to display.
const query =
props.query !== undefined
? props.query
: this._storage.get('query')
? (this._storage.get('query') as string)
: props.defaultQuery !== undefined
? props.defaultQuery
: defaultQuery;
// Get the initial query facts.
const queryFacts = getQueryFacts(props.schema, query);
// Determine the initial variables to display.
const variables =
props.variables !== undefined
? props.variables
: this._storage.get('variables');
// Determine the initial headers to display.
const headers =
props.headers !== undefined
? props.headers
: this._storage.get('headers');
// Determine the initial operationName to use.
const operationName =
props.operationName !== undefined
? props.operationName
: getSelectedOperationName(
undefined,
this._storage.get('operationName') as string,
queryFacts && queryFacts.operations,
);
// prop can be supplied to open docExplorer initially
let docExplorerOpen = props.docExplorerOpen || false;
// but then local storage state overrides it
if (this._storage.get('docExplorerOpen')) {
docExplorerOpen = this._storage.get('docExplorerOpen') === 'true';
}
// initial secondary editor pane open
let secondaryEditorOpen;
if (props.defaultVariableEditorOpen !== undefined) {
secondaryEditorOpen = props.defaultVariableEditorOpen;
} else if (props.defaultSecondaryEditorOpen !== undefined) {
secondaryEditorOpen = props.defaultSecondaryEditorOpen;
} else {
secondaryEditorOpen = Boolean(variables || headers);
}
const headerEditorEnabled = props.headerEditorEnabled ?? false;
const shouldPersistHeaders = props.shouldPersistHeaders ?? false;
// Initialize state
this.state = {
schema: props.schema,
query,
variables: variables as string,
headers: headers as string,
operationName,
docExplorerOpen,
response: props.response,
editorFlex: Number(this._storage.get('editorFlex')) || 1,
secondaryEditorOpen,
secondaryEditorHeight:
Number(this._storage.get('secondaryEditorHeight')) || 200,
variableEditorActive:
this._storage.get('variableEditorActive') === 'true' ||
props.headerEditorEnabled
? this._storage.get('headerEditorActive') !== 'true'
: secondaryEditorOpen && true,
headerEditorActive: this._storage.get('headerEditorActive') === 'true',
headerEditorEnabled,
shouldPersistHeaders,
historyPaneOpen: this._storage.get('historyPaneOpen') === 'true' || false,
docExplorerWidth:
Number(this._storage.get('docExplorerWidth')) ||
DEFAULT_DOC_EXPLORER_WIDTH,
isWaitingForResponse: false,
subscription: null,
...queryFacts,
};
}
componentDidMount() {
// Allow async state changes
this.componentIsMounted = true;
// Only fetch schema via introspection if a schema has not been
// provided, including if `null` was provided.
if (this.state.schema === undefined) {
this.fetchSchema();
}
// Utility for keeping CodeMirror correctly sized.
this.codeMirrorSizer = new CodeMirrorSizer();
global.g = this;
}
UNSAFE_componentWillMount() {
this.componentIsMounted = false;
}
// TODO: these values should be updated in a reducer imo
// eslint-disable-next-line camelcase
UNSAFE_componentWillReceiveProps(nextProps: GraphiQLProps) {
let nextSchema = this.state.schema;
let nextQuery = this.state.query;
let nextVariables = this.state.variables;
let nextHeaders = this.state.headers;
let nextOperationName = this.state.operationName;
let nextResponse = this.state.response;
if (nextProps.schema !== undefined) {
nextSchema = nextProps.schema;
}
if (nextProps.query !== undefined) {
nextQuery = nextProps.query;
}
if (nextProps.variables !== undefined) {
nextVariables = nextProps.variables;
}
if (nextProps.headers !== undefined) {
nextHeaders = nextProps.headers;
}
if (nextProps.operationName !== undefined) {
nextOperationName = nextProps.operationName;
}
if (nextProps.response !== undefined) {
nextResponse = nextProps.response;
}
if (
nextQuery &&
nextSchema &&
(nextSchema !== this.state.schema ||
nextQuery !== this.state.query ||
nextOperationName !== this.state.operationName)
) {
const updatedQueryAttributes = this._updateQueryFacts(
nextQuery,
nextOperationName,
this.state.operations,
nextSchema,
);
if (updatedQueryAttributes !== undefined) {
nextOperationName = updatedQueryAttributes.operationName;
this.setState(updatedQueryAttributes);
}
}
// If schema is not supplied via props and the fetcher changed, then
// remove the schema so fetchSchema() will be called with the new fetcher.
if (
nextProps.schema === undefined &&
nextProps.fetcher !== this.props.fetcher
) {
nextSchema = undefined;
}
this._storage.set('operationName', nextOperationName as string);
this.setState(
{
schema: nextSchema,
query: nextQuery,
variables: nextVariables,
headers: nextHeaders,
operationName: nextOperationName,
response: nextResponse,
},
() => {
if (this.state.schema === undefined) {
if (this.docExplorerComponent) {
this.docExplorerComponent.reset();
}
this.fetchSchema();
}
},
);
}
componentDidUpdate() {
// If this update caused DOM nodes to have changed sizes, update the
// corresponding CodeMirror instance sizes to match.
this.codeMirrorSizer.updateSizes([
this.queryEditorComponent,
this.variableEditorComponent,
this.headerEditorComponent,
this.resultComponent,
]);
}
// Use it when the state change is async
// TODO: Annotate correctly this function
safeSetState = (nextState: any, callback?: any): void => {
this.componentIsMounted && this.setState(nextState, callback);
};
render() {
const children = React.Children.toArray(this.props.children);
const logo = find(children, child =>
isChildComponentType(child, GraphiQL.Logo),
) || <GraphiQL.Logo />;
const toolbar = find(children, child =>
isChildComponentType(child, GraphiQL.Toolbar),
) || (
<GraphiQL.Toolbar>
<ToolbarButton
onClick={this.handlePrettifyQuery}
title="Prettify Query (Shift-Ctrl-P)"
label="Prettify"
/>
<ToolbarButton
onClick={this.handleMergeQuery}
title="Merge Query (Shift-Ctrl-M)"
label="Merge"
/>
<ToolbarButton
onClick={this.handleCopyQuery}
title="Copy Query (Shift-Ctrl-C)"
label="Copy"
/>
<ToolbarButton
onClick={this.handleToggleHistory}
title="Show History"
label="History"
/>
</GraphiQL.Toolbar>
);
const footer = find(children, child =>
isChildComponentType(child, GraphiQL.Footer),
);
const queryWrapStyle = {
WebkitFlex: this.state.editorFlex,
flex: this.state.editorFlex,
};
const docWrapStyle = {
display: 'block',
width: this.state.docExplorerWidth,
};
const docExplorerWrapClasses =
'docExplorerWrap' +
(this.state.docExplorerWidth < 200 ? ' doc-explorer-narrow' : '');
const historyPaneStyle = {
display: this.state.historyPaneOpen ? 'block' : 'none',
width: '230px',
zIndex: 7,
};
const secondaryEditorOpen = this.state.secondaryEditorOpen;
const secondaryEditorStyle = {
height: secondaryEditorOpen
? this.state.secondaryEditorHeight
: undefined,
};
return (
<div
ref={n => {
this.graphiqlContainer = n;
}}
className="graphiql-container">
<div className="historyPaneWrap" style={historyPaneStyle}>
<QueryHistory
ref={node => {
this._queryHistory = node;
}}
operationName={this.state.operationName}
query={this.state.query}
variables={this.state.variables}
onSelectQuery={this.handleSelectHistoryQuery}
storage={this._storage}
queryID={this._editorQueryID}>
<button
className="docExplorerHide"
onClick={this.handleToggleHistory}
aria-label="Close History">
{'\u2715'}
</button>
</QueryHistory>
</div>
<div className="editorWrap">
<div className="topBarWrap">
<div className="topBar">
{logo}
<ExecuteButton
isRunning={Boolean(this.state.subscription)}
onRun={this.handleRunQuery}
onStop={this.handleStopQuery}
operations={this.state.operations}
/>
{toolbar}
</div>
{!this.state.docExplorerOpen && (
<button
className="docExplorerShow"
onClick={this.handleToggleDocs}
aria-label="Open Documentation Explorer">
{'Docs'}
</button>
)}
</div>
<div
ref={n => {
this.editorBarComponent = n;
}}
className="editorBar"
onDoubleClick={this.handleResetResize}
onMouseDown={this.handleResizeStart}>
<div className="queryWrap" style={queryWrapStyle}>
<QueryEditor
ref={n => {
this.queryEditorComponent = n;
}}
schema={this.state.schema}
value={this.state.query}
onEdit={this.handleEditQuery}
onHintInformationRender={this.handleHintInformationRender}
onClickReference={this.handleClickReference}
onCopyQuery={this.handleCopyQuery}
onPrettifyQuery={this.handlePrettifyQuery}
onMergeQuery={this.handleMergeQuery}
onRunQuery={this.handleEditorRunQuery}
editorTheme={this.props.editorTheme}
readOnly={this.props.readOnly}
/>
<section
className="variable-editor secondary-editor"
style={secondaryEditorStyle}
aria-label={
this.state.variableEditorActive
? 'Query Variables'
: 'Request Headers'
}>
<div
className="secondary-editor-title variable-editor-title"
id="secondary-editor-title"
style={{
cursor: secondaryEditorOpen ? 'row-resize' : 'n-resize',
}}
onMouseDown={this.handleSecondaryEditorResizeStart}>
<div
style={{
cursor: 'pointer',
color: this.state.variableEditorActive ? '#000' : 'gray',
display: 'inline-block',
}}
onClick={this.handleOpenVariableEditorTab}
onMouseDown={this.handleTabClickPropogation}>
{'Query Variables'}
</div>
{this.state.headerEditorEnabled && (
<div
style={{
cursor: 'pointer',
color: this.state.headerEditorActive ? '#000' : 'gray',
display: 'inline-block',
marginLeft: '20px',
}}
onClick={this.handleOpenHeaderEditorTab}
onMouseDown={this.handleTabClickPropogation}>
{'Request Headers'}
</div>
)}
</div>
<VariableEditor
ref={n => {
this.variableEditorComponent = n;
}}
value={this.state.variables}
variableToType={this.state.variableToType}
onEdit={this.handleEditVariables}
onHintInformationRender={this.handleHintInformationRender}
onPrettifyQuery={this.handlePrettifyQuery}
onMergeQuery={this.handleMergeQuery}
onRunQuery={this.handleEditorRunQuery}
editorTheme={this.props.editorTheme}
readOnly={this.props.readOnly}
active={this.state.variableEditorActive}
/>
{this.state.headerEditorEnabled && (
<HeaderEditor
ref={n => {
this.headerEditorComponent = n;
}}
value={this.state.headers}
onEdit={this.handleEditHeaders}
onHintInformationRender={this.handleHintInformationRender}
onPrettifyQuery={this.handlePrettifyQuery}
onMergeQuery={this.handleMergeQuery}
onRunQuery={this.handleEditorRunQuery}
editorTheme={this.props.editorTheme}
readOnly={this.props.readOnly}
active={this.state.headerEditorActive}
/>
)}
</section>
</div>
<div className="resultWrap">
{this.state.isWaitingForResponse && (
<div className="spinner-container">
<div className="spinner" />
</div>
)}
<ResultViewer
registerRef={n => {
this.resultViewerElement = n;
}}
ref={c => {
this.resultComponent = c;
}}
value={this.state.response}
editorTheme={this.props.editorTheme}
ResultsTooltip={this.props.ResultsTooltip}
ImagePreview={ImagePreview}
/>
{footer}
</div>
</div>
</div>
{this.state.docExplorerOpen && (
<div className={docExplorerWrapClasses} style={docWrapStyle}>
<div
className="docExplorerResizer"
onDoubleClick={this.handleDocsResetResize}
onMouseDown={this.handleDocsResizeStart}
/>
<DocExplorer
ref={c => {
this.docExplorerComponent = c;
}}
schema={this.state.schema}>
<button
className="docExplorerHide"
onClick={this.handleToggleDocs}
aria-label="Close Documentation Explorer">
{'\u2715'}
</button>
</DocExplorer>
</div>
)}
</div>
);
}
// Export main windows/panes to be used separately if desired.
static Logo = GraphiQLLogo;
static Toolbar = GraphiQLToolbar;
static Footer = GraphiQLFooter;
static QueryEditor = QueryEditor;
static VariableEditor = VariableEditor;
static HeaderEditor = HeaderEditor;
static ResultViewer = ResultViewer;
// Add a button to the Toolbar.
static Button = ToolbarButton;
static ToolbarButton = ToolbarButton; // Don't break existing API.
// Add a group of buttons to the Toolbar
static Group = ToolbarGroup;
// Add a menu of items to the Toolbar.
static Menu = ToolbarMenu;
static MenuItem = ToolbarMenuItem;
// Add a select-option input to the Toolbar.
// static Select = ToolbarSelect;
// static SelectOption = ToolbarSelectOption;
/**
* Get the query editor CodeMirror instance.
*
* @public
*/
getQueryEditor() {
if (this.queryEditorComponent) {
return this.queryEditorComponent.getCodeMirror();
}
// return null
}
/**
* Get the variable editor CodeMirror instance.
*
* @public
*/
public getVariableEditor() {
if (this.variableEditorComponent) {
return this.variableEditorComponent.getCodeMirror();
}
return null;
}
/**
* Get the header editor CodeMirror instance.
*
* @public
*/
public getHeaderEditor() {
if (this.headerEditorComponent) {
return this.headerEditorComponent.getCodeMirror();
}
return null;
}
/**
* Refresh all CodeMirror instances.
*
* @public
*/
public refresh() {
if (this.queryEditorComponent) {
this.queryEditorComponent.getCodeMirror().refresh();
}
if (this.variableEditorComponent) {
this.variableEditorComponent.getCodeMirror().refresh();
}
if (this.headerEditorComponent) {
this.headerEditorComponent.getCodeMirror().refresh();
}
if (this.resultComponent) {
this.resultComponent.getCodeMirror().refresh();
}
}
/**
* Inspect the query, automatically filling in selection sets for non-leaf
* fields which do not yet have them.
*
* @public
*/
public autoCompleteLeafs() {
const { insertions, result } = fillLeafs(
this.state.schema,
this.state.query,
this.props.getDefaultFieldNames,
);
if (insertions && insertions.length > 0) {
const editor = this.getQueryEditor();
if (editor) {
editor.operation(() => {
const cursor = editor.getCursor();
const cursorIndex = editor.indexFromPos(cursor);
editor.setValue(result || '');
let added = 0;
const markers = insertions.map(({ index, string }) =>
editor.markText(
editor.posFromIndex(index + added),
editor.posFromIndex(index + (added += string.length)),
{
className: 'autoInsertedLeaf',
clearOnEnter: true,
title: 'Automatically added leaf fields',
},
),
);
setTimeout(() => markers.forEach(marker => marker.clear()), 7000);
let newCursorIndex = cursorIndex;
insertions.forEach(({ index, string }) => {
if (index < cursorIndex) {
newCursorIndex += string.length;
}
});
editor.setCursor(editor.posFromIndex(newCursorIndex));
});
}
}
return result;
}
// Private methods
private fetchSchema() {
const fetcher = this.props.fetcher;
const fetcherOpts: FetcherOpts = {
shouldPersistHeaders: Boolean(this.props.shouldPersistHeaders),
};
if (this.state.headers && this.state.headers.trim().length > 2) {
fetcherOpts.headers = JSON.parse(this.state.headers);
// if state is not present, but props are
} else if (this.props.headers) {
fetcherOpts.headers = JSON.parse(this.props.headers);
}
const fetch = observableToPromise(
fetcher(
{
query: introspectionQuery,
operationName: introspectionQueryName,
},
fetcherOpts,
),
);
if (!isPromise(fetch)) {
this.setState({
response: 'Fetcher did not return a Promise for introspection.',
});
return;
}
fetch
.then(result => {
if (typeof result !== 'string' && 'data' in result) {
return result;
}
// Try the stock introspection query first, falling back on the
// sans-subscriptions query for services which do not yet support it.
const fetch2 = observableToPromise(
fetcher(
{
query: introspectionQuerySansSubscriptions,
operationName: introspectionQueryName,
},
fetcherOpts,
),
);
if (!isPromise(fetch)) {
throw new Error(
'Fetcher did not return a Promise for introspection.',
);
}
return fetch2;
})
.then(result => {
// If a schema was provided while this fetch was underway, then
// satisfy the race condition by respecting the already
// provided schema.
if (this.state.schema !== undefined) {
return;
}
if (typeof result !== 'string' && 'data' in result) {
const schema = buildClientSchema(result.data);
const queryFacts = getQueryFacts(schema, this.state.query);
this.safeSetState({ schema, ...queryFacts });
} else {
const responseString =
typeof result === 'string' ? result : GraphiQL.formatResult(result);
this.safeSetState({
// Set schema to `null` to explicitly indicate that no schema exists.
schema: undefined,
response: responseString,
});
}
})
.catch(error => {
this.safeSetState({
schema: undefined,
response: error ? GraphiQL.formatError(error) : undefined,
});
});
}
private _fetchQuery(
query: string,
variables: string,
headers: string,
operationName: string,
shouldPersistHeaders: boolean,
cb: (value: FetcherResult) => any,
) {
const fetcher = this.props.fetcher;
let jsonVariables = null;
let jsonHeaders = null;
try {
jsonVariables =
variables && variables.trim() !== '' ? JSON.parse(variables) : null;
} catch (error) {
throw new Error(`Variables are invalid JSON: ${error.message}.`);
}
if (typeof jsonVariables !== 'object') {
throw new Error('Variables are not a JSON object.');
}
try {
jsonHeaders =
headers && headers.trim() !== '' ? JSON.parse(headers) : null;
} catch (error) {
throw new Error(`Headers are invalid JSON: ${error.message}.`);
}
if (typeof jsonHeaders !== 'object') {
throw new Error('Headers are not a JSON object.');
}
const fetch = fetcher(
{
query,
variables: jsonVariables,
operationName,
},
{ headers: jsonHeaders, shouldPersistHeaders },
);
if (isPromise(fetch)) {
// If fetcher returned a Promise, then call the callback when the promise
// resolves, otherwise handle the error.
fetch.then(cb).catch(error => {
this.safeSetState({
isWaitingForResponse: false,
response: error ? GraphiQL.formatError(error) : undefined,
});
});
} else if (isObservable(fetch)) {
// If the fetcher returned an Observable, then subscribe to it, calling
// the callback on each next value, and handling both errors and the
// completion of the Observable. Returns a Subscription object.
const subscription = fetch.subscribe({
next: cb,
error: (error: Error) => {
this.safeSetState({
isWaitingForResponse: false,
response: error ? GraphiQL.formatError(error) : undefined,
subscription: null,
});
},
complete: () => {
this.safeSetState({
isWaitingForResponse: false,
subscription: null,
});
},
});
return subscription;
} else {
throw new Error('Fetcher did not return Promise or Observable.');
}
}
handleClickReference = (reference: GraphQLType) => {
this.setState({ docExplorerOpen: true }, () => {
if (this.docExplorerComponent) {
this.docExplorerComponent.showDocForReference(reference);
}
});
this._storage.set(
'docExplorerOpen',
JSON.stringify(this.state.docExplorerOpen),
);
};
handleRunQuery = (selectedOperationName?: string) => {
this._editorQueryID++;
const queryID = this._editorQueryID;
// Use the edited query after autoCompleteLeafs() runs or,
// in case autoCompletion fails (the function returns undefined),
// the current query from the editor.
const editedQuery = this.autoCompleteLeafs() || this.state.query;
const variables = this.state.variables;
const headers = this.state.headers;
const shouldPersistHeaders = this.state.shouldPersistHeaders;
let operationName = this.state.operationName;
// If an operation was explicitly provided, different from the current
// operation name, then report that it changed.
if (selectedOperationName && selectedOperationName !== operationName) {
operationName = selectedOperationName;
this.handleEditOperationName(operationName);
}
try {
this.setState({
isWaitingForResponse: true,
response: undefined,
operationName,
});
this._storage.set('operationName', operationName as string);
if (this._queryHistory) {
this._queryHistory.updateHistory(
editedQuery,
variables,
headers,
operationName,
);
}
// _fetchQuery may return a subscription.
const subscription = this._fetchQuery(
editedQuery as string,