-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathApp.tsx
197 lines (179 loc) · 5.75 KB
/
App.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
import { ReactElement, useEffect, useRef, useState, StrictMode } from 'react';
import { getIntrospectionQuery, IntrospectionQuery } from 'graphql';
import { Uri, editor, KeyMod, KeyCode, languages } from 'monaco-editor';
import { initializeMode } from 'monaco-graphql/src/initializeMode';
import { createGraphiQLFetcher, SyncFetcherResult } from '@graphiql/toolkit';
import * as JSONC from 'jsonc-parser';
import { debounce } from './debounce';
const fetcher = createGraphiQLFetcher({
url: 'https://countries.trevorblades.com',
});
const defaultOperations =
localStorage.getItem('operations') ??
`# cmd/ctrl + return/enter will execute the op,
# same in variables editor below
# also available via context menu & f1 command palette
query($code: ID!) {
country(code: $code) {
awsRegion
native
phone
}
}`;
const defaultVariables =
localStorage.getItem('variables') ??
`{
// 'code' will appear here as autocomplete,
// and because the default value is 0, will
// complete as such
$1
}`;
async function getSchema(): Promise<SyncFetcherResult> {
return fetcher({
query: getIntrospectionQuery(),
operationName: 'IntrospectionQuery',
});
}
function getOrCreateModel(uri: string, value: string): editor.ITextModel {
return (
editor.getModel(Uri.file(uri)) ??
editor.createModel(value, uri.split('.').pop(), Uri.file(uri))
);
}
async function execOperation(): Promise<void> {
const variables = editor.getModel(Uri.file('variables.json'))!.getValue();
const operations = editor.getModel(Uri.file('operation.graphql'))!.getValue();
const resultsModel = editor.getModel(Uri.file('results.json'));
const result = await fetcher({
query: operations,
variables: JSONC.parse(variables),
});
// TODO: this demo only supports a single iteration for http GET/POST,
// no multipart or subscriptions yet.
// @ts-expect-error
const data = await result.next();
resultsModel?.setValue(JSON.stringify(data.value, null, 2));
}
const queryAction = {
id: 'graphql-run',
label: 'Run Operation',
contextMenuOrder: 0,
contextMenuGroupId: 'graphql',
keybindings: [
// eslint-disable-next-line no-bitwise
KeyMod.CtrlCmd | KeyCode.Enter,
],
run: execOperation,
};
// set these early on so that initial variables with comments don't flash an error
languages.json.jsonDefaults.setDiagnosticsOptions({
allowComments: true,
trailingCommas: 'ignore',
});
type Editor = editor.IStandaloneCodeEditor | null;
export default function App(): ReactElement {
const operationsRef = useRef<HTMLDivElement>(null);
const variablesRef = useRef<HTMLDivElement>(null);
const resultsRef = useRef<HTMLDivElement>(null);
const [queryEditor, setQueryEditor] = useState<Editor>(null);
const [variablesEditor, setVariablesEditor] = useState<Editor>(null);
const [resultsViewer, setResultsViewer] = useState<Editor>(null);
const [schema, setSchema] = useState<IntrospectionQuery | null>(null);
const [loading, setLoading] = useState(false);
/**
* Create the models & editors
*/
useEffect(() => {
const queryModel = getOrCreateModel('operation.graphql', defaultOperations);
const variablesModel = getOrCreateModel('variables.json', defaultVariables);
const resultsModel = getOrCreateModel('results.json', '{}');
if (!queryEditor) {
setQueryEditor(
editor.create(operationsRef.current!, {
theme: 'vs-dark',
model: queryModel,
language: 'graphql',
}),
);
}
if (!variablesEditor) {
setVariablesEditor(
editor.create(variablesRef.current!, {
theme: 'vs-dark',
model: variablesModel,
}),
);
}
if (!resultsViewer) {
setResultsViewer(
editor.create(resultsRef.current!, {
theme: 'vs-dark',
model: resultsModel,
readOnly: true,
smoothScrolling: true,
}),
);
}
queryModel.onDidChangeContent(
debounce(300, () => {
localStorage.setItem('operations', queryModel.getValue());
}),
);
variablesModel.onDidChangeContent(
debounce(300, () => {
localStorage.setItem('variables', variablesModel.getValue());
}),
);
// eslint-disable-next-line react-hooks/exhaustive-deps -- only run once on mount
}, []);
useEffect(() => {
queryEditor?.addAction(queryAction);
variablesEditor?.addAction(queryAction);
}, [queryEditor, variablesEditor]);
/**
* Handle the initial schema load
*/
useEffect(() => {
if (schema || loading) {
return;
}
setLoading(true);
void getSchema().then(data => {
const introspectionJSON =
'data' in data && (data.data as unknown as IntrospectionQuery);
if (!introspectionJSON) {
throw new Error(
'this demo does not support subscriptions or http multipart yet',
);
}
initializeMode({
diagnosticSettings: {
validateVariablesJSON: {
[Uri.file('operation.graphql').toString()]: [
Uri.file('variables.json').toString(),
],
},
jsonDiagnosticSettings: {
validate: true,
schemaValidation: 'error',
// set these again, because we are entirely re-setting them here
allowComments: true,
trailingCommas: 'ignore',
},
},
schemas: [{ introspectionJSON, uri: 'myschema.graphql' }],
});
setSchema(introspectionJSON);
setLoading(false);
});
}, [schema, loading]);
return (
<StrictMode>
<div id="left-pane" className="pane">
<div ref={operationsRef} className="editor" />
<div ref={variablesRef} className="editor" />
</div>
<div ref={resultsRef} id="right-pane" className="pane editor" />
</StrictMode>
);
}