-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
context.tsx
502 lines (461 loc) · 14.8 KB
/
context.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
import {
DocumentNode,
FragmentDefinitionNode,
OperationDefinitionNode,
parse,
ValidationRule,
visit,
} from 'graphql';
import { VariableToType } from 'graphql-language-service';
import { ReactNode, useCallback, useMemo, useState } from 'react';
import { useStorageContext } from '../storage';
import { createContextHook, createNullableContext } from '../utility/context';
import { STORAGE_KEY as STORAGE_KEY_HEADERS } from './header-editor';
import { useSynchronizeValue } from './hooks';
import { STORAGE_KEY_QUERY } from './query-editor';
import {
createTab,
getDefaultTabState,
setPropertiesInActiveTab,
TabDefinition,
TabsState,
TabState,
useSetEditorValues,
useStoreTabs,
useSynchronizeActiveTabValues,
} from './tabs';
import { CodeMirrorEditor } from './types';
import { STORAGE_KEY as STORAGE_KEY_VARIABLES } from './variable-editor';
export type CodeMirrorEditorWithOperationFacts = CodeMirrorEditor & {
documentAST: DocumentNode | null;
operationName: string | null;
operations: OperationDefinitionNode[] | null;
variableToType: VariableToType | null;
};
export type EditorContextType = TabsState & {
/**
* Add a new tab.
*/
addTab(): void;
/**
* Switch to a different tab.
* @param index The index of the tab that should be switched to.
*/
changeTab(index: number): void;
/**
* Close a tab. If the currently active tab is closed the tab before it will
* become active. If there is no tab before the closed one, the tab after it
* will become active.
* @param index The index of the tab that should be closed.
*/
closeTab(index: number): void;
/**
* Update the state for the tab that is currently active. This will be
* reflected in the `tabs` object and the state will be persisted in storage
* (if available).
* @param partialTab A partial tab state object that will override the
* current values. The properties `id`, `hash` and `title` cannot be changed.
*/
updateActiveTabValues(
partialTab: Partial<Omit<TabState, 'id' | 'hash' | 'title'>>,
): void;
/**
* The CodeMirror editor instance for the headers editor.
*/
headerEditor: CodeMirrorEditor | null;
/**
* The CodeMirror editor instance for the query editor. This editor also
* stores the operation facts that are derived from the current editor
* contents.
*/
queryEditor: CodeMirrorEditorWithOperationFacts | null;
/**
* The CodeMirror editor instance for the response editor.
*/
responseEditor: CodeMirrorEditor | null;
/**
* The CodeMirror editor instance for the variables editor.
*/
variableEditor: CodeMirrorEditor | null;
/**
* Set the CodeMirror editor instance for the headers editor.
*/
setHeaderEditor(newEditor: CodeMirrorEditor): void;
/**
* Set the CodeMirror editor instance for the query editor.
*/
setQueryEditor(newEditor: CodeMirrorEditorWithOperationFacts): void;
/**
* Set the CodeMirror editor instance for the response editor.
*/
setResponseEditor(newEditor: CodeMirrorEditor): void;
/**
* Set the CodeMirror editor instance for the variables editor.
*/
setVariableEditor(newEditor: CodeMirrorEditor): void;
/**
* Changes the operation name and invokes the `onEditOperationName` callback.
*/
setOperationName(operationName: string): void;
/**
* The contents of the headers editor when initially rendering the provider
* component.
*/
initialHeaders: string;
/**
* The contents of the query editor when initially rendering the provider
* component.
*/
initialQuery: string;
/**
* The contents of the response editor when initially rendering the provider
* component.
*/
initialResponse: string;
/**
* The contents of the variables editor when initially rendering the provider
* component.
*/
initialVariables: string;
/**
* A map of fragment definitions using the fragment name as key which are
* made available to include in the query.
*/
externalFragments: Map<string, FragmentDefinitionNode>;
/**
* A list of custom validation rules that are run in addition to the rules
* provided by the GraphQL spec.
*/
validationRules: ValidationRule[];
/**
* If the contents of the headers editor are persisted in storage.
*/
shouldPersistHeaders: boolean;
};
export const EditorContext =
createNullableContext<EditorContextType>('EditorContext');
export type EditorContextProviderProps = {
children: ReactNode;
/**
* The initial contents of the query editor when loading GraphiQL and there
* is no other source for the editor state. Other sources can be:
* - The `query` prop
* - The value persisted in storage
* These default contents will only be used for the first tab. When opening
* more tabs the query editor will start out empty.
*/
defaultQuery?: string;
/**
* With this prop you can pass so-called "external" fragments that will be
* included in the query document (depending on usage). You can either pass
* the fragments using SDL (passing a string) or you can pass a list of
* `FragmentDefinitionNode` objects.
*/
externalFragments?: string | FragmentDefinitionNode[];
/**
* This prop can be used to set the contents of the headers editor. Every
* time this prop changes, the contents of the headers editor are replaced.
* Note that the editor contents can be changed in between these updates by
* typing in the editor.
*/
headers?: string;
/**
* This prop can be used to defined the initial set of tabs with their queries,
* variables and headers.
*
* @example
* ```tsx
* <GraphiQL
* initialTabs={[
* { query: 'query myExampleQuery {}' },
* { query: '{ id }' }
* ]}
* />
*```
*/
initialTabs?: TabDefinition[];
/**
* Invoked when the operation name changes. Possible triggers are:
* - Editing the contents of the query editor
* - Selecting a operation for execution in a document that contains multiple
* operation definitions
* @param operationName The operation name after it has been changed.
*/
onEditOperationName?(operationName: string): void;
/**
* Invoked when the state of the tabs changes. Possible triggers are:
* - Updating any editor contents inside the currently active tab
* - Adding a tab
* - Switching to a different tab
* - Closing a tab
* @param tabState The tabs state after it has been updated.
*/
onTabChange?(tabState: TabsState): void;
/**
* This prop can be used to set the contents of the query editor. Every time
* this prop changes, the contents of the query editor are replaced. Note
* that the editor contents can be changed in between these updates by typing
* in the editor.
*/
query?: string;
/**
* This prop can be used to set the contents of the response editor. Every
* time this prop changes, the contents of the response editor are replaced.
* Note that the editor contents can change in between these updates by
* executing queries that will show a response.
*/
response?: string;
/**
* This prop toggles if the contents of the headers editor are persisted in
* storage.
* @default false
*/
shouldPersistHeaders?: boolean;
/**
* This prop accepts custom validation rules for GraphQL documents that are
* run against the contents of the query editor (in addition to the rules
* that are specified in the GraphQL spec).
*/
validationRules?: ValidationRule[];
/**
* This prop can be used to set the contents of the variables editor. Every
* time this prop changes, the contents of the variables editor are replaced.
* Note that the editor contents can be changed in between these updates by
* typing in the editor.
*/
variables?: string;
};
export function EditorContextProvider(props: EditorContextProviderProps) {
const storage = useStorageContext();
const [headerEditor, setHeaderEditor] = useState<CodeMirrorEditor | null>(
null,
);
const [queryEditor, setQueryEditor] =
useState<CodeMirrorEditorWithOperationFacts | null>(null);
const [responseEditor, setResponseEditor] = useState<CodeMirrorEditor | null>(
null,
);
const [variableEditor, setVariableEditor] = useState<CodeMirrorEditor | null>(
null,
);
useSynchronizeValue(headerEditor, props.headers);
useSynchronizeValue(queryEditor, props.query);
useSynchronizeValue(responseEditor, props.response);
useSynchronizeValue(variableEditor, props.variables);
const storeTabs = useStoreTabs({
storage,
shouldPersistHeaders: props.shouldPersistHeaders,
});
// We store this in state but never update it. By passing a function we only
// need to compute it lazily during the initial render.
const [initialState] = useState(() => {
const query = props.query ?? storage?.get(STORAGE_KEY_QUERY) ?? null;
const variables =
props.variables ?? storage?.get(STORAGE_KEY_VARIABLES) ?? null;
const headers = props.headers ?? storage?.get(STORAGE_KEY_HEADERS) ?? null;
const response = props.response ?? '';
const tabState = getDefaultTabState({
query,
variables,
headers,
initialTabs: props.initialTabs,
defaultQuery: props.defaultQuery || DEFAULT_QUERY,
storage,
});
storeTabs(tabState);
return {
query:
query ??
(tabState.activeTabIndex === 0 ? tabState.tabs[0].query : null) ??
'',
variables: variables ?? '',
headers: headers ?? '',
response,
tabState,
};
});
const [tabState, setTabState] = useState<TabsState>(initialState.tabState);
const synchronizeActiveTabValues = useSynchronizeActiveTabValues({
queryEditor,
variableEditor,
headerEditor,
responseEditor,
});
const setEditorValues = useSetEditorValues({
queryEditor,
variableEditor,
headerEditor,
responseEditor,
});
const { onTabChange } = props;
const addTab = useCallback<EditorContextType['addTab']>(() => {
setTabState(current => {
// Make sure the current tab stores the latest values
const updatedValues = synchronizeActiveTabValues(current);
const updated = {
tabs: [...updatedValues.tabs, createTab()],
activeTabIndex: updatedValues.tabs.length,
};
storeTabs(updated);
setEditorValues(updated.tabs[updated.activeTabIndex]);
onTabChange?.(updated);
return updated;
});
}, [onTabChange, setEditorValues, storeTabs, synchronizeActiveTabValues]);
const changeTab = useCallback<EditorContextType['changeTab']>(
index => {
setTabState(current => {
const updated = {
...synchronizeActiveTabValues(current),
activeTabIndex: index,
};
storeTabs(updated);
setEditorValues(updated.tabs[updated.activeTabIndex]);
onTabChange?.(updated);
return updated;
});
},
[onTabChange, setEditorValues, storeTabs, synchronizeActiveTabValues],
);
const closeTab = useCallback<EditorContextType['closeTab']>(
index => {
setTabState(current => {
const updated = {
tabs: current.tabs.filter((_tab, i) => index !== i),
activeTabIndex: Math.max(current.activeTabIndex - 1, 0),
};
storeTabs(updated);
setEditorValues(updated.tabs[updated.activeTabIndex]);
onTabChange?.(updated);
return updated;
});
},
[onTabChange, setEditorValues, storeTabs],
);
const updateActiveTabValues = useCallback<
EditorContextType['updateActiveTabValues']
>(
partialTab => {
setTabState(current => {
const updated = setPropertiesInActiveTab(current, partialTab);
storeTabs(updated);
onTabChange?.(updated);
return updated;
});
},
[onTabChange, storeTabs],
);
const { onEditOperationName } = props;
const setOperationName = useCallback<EditorContextType['setOperationName']>(
operationName => {
if (!queryEditor) {
return;
}
queryEditor.operationName = operationName;
updateActiveTabValues({ operationName });
onEditOperationName?.(operationName);
},
[onEditOperationName, queryEditor, updateActiveTabValues],
);
const externalFragments = useMemo(() => {
const map = new Map<string, FragmentDefinitionNode>();
if (Array.isArray(props.externalFragments)) {
for (const fragment of props.externalFragments) {
map.set(fragment.name.value, fragment);
}
} else if (typeof props.externalFragments === 'string') {
visit(parse(props.externalFragments, {}), {
FragmentDefinition(fragment) {
map.set(fragment.name.value, fragment);
},
});
} else if (props.externalFragments) {
throw new Error(
'The `externalFragments` prop must either be a string that contains the fragment definitions in SDL or a list of FragmentDefinitionNode objects.',
);
}
return map;
}, [props.externalFragments]);
const validationRules = useMemo(
() => props.validationRules || [],
[props.validationRules],
);
const value = useMemo<EditorContextType>(
() => ({
...tabState,
addTab,
changeTab,
closeTab,
updateActiveTabValues,
headerEditor,
queryEditor,
responseEditor,
variableEditor,
setHeaderEditor,
setQueryEditor,
setResponseEditor,
setVariableEditor,
setOperationName,
initialQuery: initialState.query,
initialVariables: initialState.variables,
initialHeaders: initialState.headers,
initialResponse: initialState.response,
externalFragments,
validationRules,
shouldPersistHeaders: props.shouldPersistHeaders || false,
}),
[
tabState,
addTab,
changeTab,
closeTab,
updateActiveTabValues,
headerEditor,
queryEditor,
responseEditor,
variableEditor,
setOperationName,
initialState,
externalFragments,
validationRules,
props.shouldPersistHeaders,
],
);
return (
<EditorContext.Provider value={value}>
{props.children}
</EditorContext.Provider>
);
}
export const useEditorContext = createContextHook(EditorContext);
const DEFAULT_QUERY = `# Welcome to GraphiQL
#
# GraphiQL is an in-browser tool for writing, validating, and
# testing GraphQL queries.
#
# Type queries into this side of the screen, and you will see intelligent
# typeaheads aware of the current GraphQL type schema and live syntax and
# validation errors highlighted within the text.
#
# GraphQL queries typically start with a "{" character. Lines that start
# with a # are ignored.
#
# An example GraphQL query might look like:
#
# {
# field(arg: "value") {
# subField
# }
# }
#
# Keyboard shortcuts:
#
# Prettify query: Shift-Ctrl-P (or press the prettify button)
#
# Merge fragments: Shift-Ctrl-M (or press the merge button)
#
# Run Query: Ctrl-Enter (or press the play button)
#
# Auto Complete: Ctrl-Space (or just start typing)
#
`;