-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy patheditor.ts
More file actions
540 lines (496 loc) · 14.8 KB
/
editor.ts
File metadata and controls
540 lines (496 loc) · 14.8 KB
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
import type { StateCreator } from 'zustand';
import type {
FragmentDefinitionNode,
OperationDefinitionNode,
DocumentNode,
} from 'graphql';
import type { OperationFacts } from 'graphql-language-service';
import { MaybePromise, mergeAst } from '@graphiql/toolkit';
import { print } from 'graphql';
import {
createTab,
setPropertiesInActiveTab,
TabDefinition,
TabsState,
TabState,
clearHeadersFromTabs,
serializeTabState,
} from '../utility/tabs';
import type { SlicesWithActions, MonacoEditor } from '../types';
import { debounce, formatJSONC } from '../utility';
import { STORAGE_KEY } from '../constants';
export interface EditorSlice extends TabsState {
/**
* Unique ID of the GraphiQL instance, which will be suffixed to the URIs for operations,
* variables, headers, and response editors.
*
* @see https://github.com/microsoft/monaco-editor#uris
*/
uriInstanceId: string;
/**
* The Monaco Editor instance used in the request headers editor, used to edit HTTP headers.
*/
headerEditor?: MonacoEditor;
/**
* The Monaco Editor instance used in the operation editor.
*/
queryEditor?: MonacoEditor;
/**
* The Monaco Editor instance used in the response editor.
*/
responseEditor?: MonacoEditor;
/**
* The Monaco Editor instance used in the variables editor.
*/
variableEditor?: MonacoEditor;
/**
* The contents of the request headers editor when initially rendering the provider
* component.
*/
initialHeaders: string;
/**
* The contents of the operation editor when initially rendering the provider
* component.
*/
initialQuery: 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 a key which are
* made available to include in the query.
*/
externalFragments: Map<string, FragmentDefinitionNode>;
/**
* If the contents of the request headers editor are persisted in storage.
*/
shouldPersistHeaders: boolean;
/**
* The initial content of the operation editor when loading GraphiQL and there is
* no saved query in storage and no `initialQuery` prop.
*
* This value is used only for the first tab. Additional tabs will open with
* an empty operation editor.
*
* @default "# Welcome to GraphiQL..."
*/
defaultQuery?: string;
/**
* Invoked when the operation name changes. Possible triggers are:
* - Editing the contents of the operation editor
* - Selecting an 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 tab state after it has been updated.
*/
onTabChange?(tabState: TabsState): void;
/**
* Headers to be set when opening a new tab.
*/
defaultHeaders?: string;
/**
* Invoked when the current contents of the operation editor are copied to the
* clipboard.
* @param query - The content that has been copied.
*/
onCopyQuery?: (query: string) => void;
/**
* Invoked when the prettify callback is invoked.
* @param query - The current value of the operation editor.
* @default
* import prettier from 'prettier/standalone'
*
* prettier.format(query, { parser: 'graphql' })
* @returns The formatted query.
*/
onPrettifyQuery: (query: string) => MaybePromise<string>;
// Operation facts that are derived from the operation editor.
/**
* @remarks from graphiql 5
*/
documentAST?: OperationFacts['documentAST'];
/**
* @remarks from graphiql 5
*/
operationName?: string;
/**
* @remarks from graphiql 5
*/
operations?: OperationFacts['operations'];
}
export interface EditorActions {
/**
* 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;
/**
* Move a tab to a new spot.
* @param newOrder - The new order for the tabs.
*/
moveTab(newOrder: TabState[]): 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;
/**
* Set the Monaco Editor instance used in the specified editor.
*/
setEditor(
state: Pick<
EditorSlice,
'headerEditor' | 'queryEditor' | 'responseEditor' | 'variableEditor'
>,
): void;
/**
* Changes the operation name and invokes the `onEditOperationName` callback.
*/
setOperationName(operationName: string): void;
/**
* Changes if headers should be persisted.
*/
setShouldPersistHeaders(persist: boolean): void;
storeTabs(tabsState: TabsState): void;
setOperationFacts(facts: {
documentAST?: DocumentNode;
operationName?: string;
operations?: OperationDefinitionNode[];
}): void;
/**
* Copy a query to clipboard.
*/
copyQuery: () => Promise<void>;
/**
* Merge fragments definitions into operation definition.
*/
mergeQuery: () => void;
/**
* Prettify query, variables and request headers editors.
*/
prettifyEditors: () => Promise<void>;
}
export interface EditorProps extends Pick<
EditorSlice,
| 'onTabChange'
| 'onEditOperationName'
| 'defaultHeaders'
| 'defaultQuery'
| 'onCopyQuery'
> {
/**
* 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 define the default set of tabs, with their
* queries, variables, and headers. It will be used as default only if
* there is no tab state persisted in storage.
*
* @example
* ```tsx
* <GraphiQL
* defaultTabs={[
* { query: 'query myExampleQuery {}' },
* { query: '{ id }' }
* ]}
* />
*```
*/
defaultTabs?: TabDefinition[];
/**
* This prop toggles if the contents of the request headers editor are persisted in
* storage.
* @default false
*/
shouldPersistHeaders?: boolean;
onPrettifyQuery?: EditorSlice['onPrettifyQuery'];
initialQuery?: EditorSlice['initialQuery'];
initialVariables?: EditorSlice['initialVariables'];
initialHeaders?: EditorSlice['initialHeaders'];
}
type CreateEditorSlice = (
initial: Pick<
EditorSlice,
| 'shouldPersistHeaders'
| 'tabs'
| 'activeTabIndex'
| 'initialQuery'
| 'initialVariables'
| 'initialHeaders'
| 'onEditOperationName'
| 'externalFragments'
| 'onTabChange'
| 'defaultQuery'
| 'defaultHeaders'
| 'onPrettifyQuery'
| 'onCopyQuery'
| 'uriInstanceId'
>,
) => StateCreator<
SlicesWithActions,
[],
[],
EditorSlice & { actions: EditorActions }
>;
export const createEditorSlice: CreateEditorSlice = initial => (set, get) => {
function setEditorValues({
query,
variables,
headers,
response,
}: {
query: string | null;
variables?: string | null;
headers?: string | null;
response: string | null;
}) {
const {
queryEditor,
variableEditor,
headerEditor,
responseEditor,
defaultHeaders,
} = get();
queryEditor?.setValue(query ?? '');
variableEditor?.setValue(variables ?? '');
headerEditor?.setValue(headers ?? defaultHeaders ?? '');
responseEditor?.setValue(response ?? '');
}
function synchronizeActiveTabValues(tabsState: TabsState): TabsState {
const {
queryEditor,
variableEditor,
headerEditor,
responseEditor,
operationName,
} = get();
return setPropertiesInActiveTab(tabsState, {
query: queryEditor?.getValue() ?? null,
variables: variableEditor?.getValue() ?? null,
headers: headerEditor?.getValue() ?? null,
response: responseEditor?.getValue() ?? null,
operationName: operationName ?? null,
});
}
const $actions: EditorActions = {
addTab() {
set(({ defaultHeaders, onTabChange, tabs, activeTabIndex, actions }) => {
// Make sure the current tab stores the latest values
const updatedValues = synchronizeActiveTabValues({
tabs,
activeTabIndex,
});
const updated = {
tabs: [...updatedValues.tabs, createTab({ headers: defaultHeaders })],
activeTabIndex: updatedValues.tabs.length,
};
actions.storeTabs(updated);
setEditorValues(updated.tabs[updated.activeTabIndex]!);
onTabChange?.(updated);
return updated;
});
},
changeTab(index) {
set(({ actions, onTabChange, tabs }) => {
actions.stop();
const updated = {
tabs,
activeTabIndex: index,
};
actions.storeTabs(updated);
setEditorValues(updated.tabs[updated.activeTabIndex]!);
onTabChange?.(updated);
return updated;
});
},
moveTab(newOrder) {
set(({ onTabChange, actions, tabs, activeTabIndex }) => {
const activeTab = tabs[activeTabIndex]!;
const updated = {
tabs: newOrder,
activeTabIndex: newOrder.indexOf(activeTab),
};
actions.storeTabs(updated);
setEditorValues(updated.tabs[updated.activeTabIndex]!);
onTabChange?.(updated);
return updated;
});
},
closeTab(index) {
set(({ activeTabIndex, onTabChange, actions, tabs }) => {
if (activeTabIndex === index) {
actions.stop();
}
const updated = {
tabs: tabs.filter((_tab, i) => index !== i),
activeTabIndex: Math.max(activeTabIndex - 1, 0),
};
actions.storeTabs(updated);
setEditorValues(updated.tabs[updated.activeTabIndex]!);
onTabChange?.(updated);
return updated;
});
},
updateActiveTabValues(partialTab) {
set(({ activeTabIndex, tabs, onTabChange, actions }) => {
const updated = setPropertiesInActiveTab(
{ tabs, activeTabIndex },
partialTab,
);
actions.storeTabs(updated);
onTabChange?.(updated);
return updated;
});
},
setEditor({ headerEditor, queryEditor, responseEditor, variableEditor }) {
const entries = Object.entries({
headerEditor,
queryEditor,
responseEditor,
variableEditor,
}).filter(([_key, value]) => value);
const newState = Object.fromEntries(entries);
set(newState);
},
setOperationName(operationName) {
set(({ onEditOperationName, actions }) => {
actions.updateActiveTabValues({ operationName });
onEditOperationName?.(operationName);
return { operationName };
});
},
setShouldPersistHeaders(persist) {
const { headerEditor, tabs, activeTabIndex, storage } = get();
if (persist) {
storage.set(STORAGE_KEY.headers, headerEditor?.getValue() ?? '');
const serializedTabs = serializeTabState(
{ tabs, activeTabIndex },
true,
);
storage.set(STORAGE_KEY.tabs, serializedTabs);
} else {
storage.set(STORAGE_KEY.headers, '');
clearHeadersFromTabs(storage);
}
storage.set(STORAGE_KEY.persistHeaders, persist.toString());
set({ shouldPersistHeaders: persist });
},
storeTabs({ tabs, activeTabIndex }) {
const { shouldPersistHeaders, storage } = get();
const store = debounce(500, (value: string) => {
storage.set(STORAGE_KEY.tabs, value);
});
store(serializeTabState({ tabs, activeTabIndex }, shouldPersistHeaders));
},
setOperationFacts({ documentAST, operationName, operations }) {
set({
documentAST,
operationName,
operations,
});
},
async copyQuery() {
const { queryEditor, onCopyQuery } = get();
if (!queryEditor) {
return;
}
const query = queryEditor.getValue();
onCopyQuery?.(query);
try {
await navigator.clipboard.writeText(query);
} catch (error) {
// eslint-disable-next-line no-console
console.warn('Failed to copy query!', error);
}
},
async prettifyEditors() {
const { queryEditor, headerEditor, variableEditor, onPrettifyQuery } =
get();
if (variableEditor) {
try {
const content = variableEditor.getValue();
const formatted = await formatJSONC(content);
if (formatted !== content) {
variableEditor.setValue(formatted);
}
} catch (error) {
// eslint-disable-next-line no-console
console.warn(
'Parsing variables JSON failed, skip prettification.',
error,
);
}
}
if (headerEditor) {
try {
const content = headerEditor.getValue();
const formatted = await formatJSONC(content);
if (formatted !== content) {
headerEditor.setValue(formatted);
}
} catch (error) {
// eslint-disable-next-line no-console
console.warn(
'Parsing headers JSON failed, skip prettification.',
error,
);
}
}
if (!queryEditor) {
return;
}
try {
const content = queryEditor.getValue();
const formatted = await onPrettifyQuery(content);
if (formatted !== content) {
queryEditor.setValue(formatted);
}
} catch (error) {
// eslint-disable-next-line no-console
console.warn('Parsing query failed, skip prettification.', error);
}
},
mergeQuery() {
const { queryEditor, documentAST, schema } = get();
const query = queryEditor?.getValue();
if (!documentAST || !query) {
return;
}
queryEditor!.setValue(print(mergeAst(documentAST, schema)));
},
};
return {
...initial,
actions: $actions,
};
};