-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathhooks.ts
467 lines (423 loc) · 13 KB
/
hooks.ts
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
import { fillLeafs, GetDefaultFieldNamesFn, mergeAst } from '@graphiql/toolkit';
import type { EditorChange, EditorConfiguration } from 'codemirror';
import type { SchemaReference } from 'codemirror-graphql/utils/SchemaReference';
import copyToClipboard from 'copy-to-clipboard';
import { parse, print } from 'graphql';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useExplorerContext } from '../explorer';
import { usePluginContext } from '../plugin';
import { useSchemaContext } from '../schema';
import { useStorageContext } from '../storage';
import debounce from '../utility/debounce';
import { onHasCompletion } from './completion';
import { useEditorContext } from './context';
import { CodeMirrorEditor } from './types';
export function useSynchronizeValue(
editor: CodeMirrorEditor | null,
value: string | undefined,
) {
useEffect(() => {
if (editor && typeof value === 'string' && value !== editor.getValue()) {
editor.setValue(value);
}
}, [editor, value]);
}
export function useSynchronizeOption<K extends keyof EditorConfiguration>(
editor: CodeMirrorEditor | null,
option: K,
value: EditorConfiguration[K],
) {
useEffect(() => {
if (editor) {
editor.setOption(option, value);
}
}, [editor, option, value]);
}
export function useChangeHandler(
editor: CodeMirrorEditor | null,
callback: ((value: string) => void) | undefined,
storageKey: string | null,
tabProperty: 'variables' | 'headers',
caller: Function,
) {
const { updateActiveTabValues } = useEditorContext({ nonNull: true, caller });
const storage = useStorageContext();
useEffect(() => {
if (!editor) {
return;
}
const store = debounce(500, (value: string) => {
if (!storage || storageKey === null) {
return;
}
storage.set(storageKey, value);
});
const updateTab = debounce(100, (value: string) => {
updateActiveTabValues({ [tabProperty]: value });
});
const handleChange = (
editorInstance: CodeMirrorEditor,
changeObj: EditorChange | undefined,
) => {
// When we signal a change manually without actually changing anything
// we don't want to invoke the callback.
if (!changeObj) {
return;
}
const newValue = editorInstance.getValue();
store(newValue);
updateTab(newValue);
callback?.(newValue);
};
editor.on('change', handleChange);
return () => editor.off('change', handleChange);
}, [
callback,
editor,
storage,
storageKey,
tabProperty,
updateActiveTabValues,
]);
}
export function useCompletion(
editor: CodeMirrorEditor | null,
callback: ((reference: SchemaReference) => void) | null,
caller: Function,
) {
const { schema } = useSchemaContext({ nonNull: true, caller });
const explorer = useExplorerContext();
const plugin = usePluginContext();
useEffect(() => {
if (!editor) {
return;
}
const handleCompletion = (
instance: CodeMirrorEditor,
changeObj?: EditorChange,
) => {
onHasCompletion(instance, changeObj, schema, explorer, plugin, type => {
callback?.({ kind: 'Type', type, schema: schema || undefined });
});
};
editor.on(
// @ts-expect-error @TODO additional args for hasCompletion event
'hasCompletion',
handleCompletion,
);
return () =>
editor.off(
// @ts-expect-error @TODO additional args for hasCompletion event
'hasCompletion',
handleCompletion,
);
}, [callback, editor, explorer, plugin, schema]);
}
type EmptyCallback = () => void;
export function useKeyMap(
editor: CodeMirrorEditor | null,
keys: string[],
callback: EmptyCallback | undefined,
) {
useEffect(() => {
if (!editor) {
return;
}
const handleRemoveKeys = () => {
for (const key of keys) {
editor.removeKeyMap(key);
}
};
handleRemoveKeys();
if (callback) {
const keyMap: Record<string, EmptyCallback> = {};
for (const key of keys) {
keyMap[key] = () => callback();
}
editor.addKeyMap(keyMap);
}
return handleRemoveKeys;
}, [editor, keys, callback]);
}
export type UseCopyQueryArgs = {
/**
* This is only meant to be used internally in `@graphiql/react`.
*/
caller?: Function;
/**
* Invoked when the current contents of the query editor are copied to the
* clipboard.
* @param query The content that has been copied.
*/
onCopyQuery?: (query: string) => void;
};
export function useCopyQuery({ caller, onCopyQuery }: UseCopyQueryArgs = {}) {
const { queryEditor } = useEditorContext({
nonNull: true,
caller: caller || useCopyQuery,
});
return useCallback(() => {
if (!queryEditor) {
return;
}
const query = queryEditor.getValue();
copyToClipboard(query);
onCopyQuery?.(query);
}, [queryEditor, onCopyQuery]);
}
type UseMergeQueryArgs = {
/**
* This is only meant to be used internally in `@graphiql/react`.
*/
caller?: Function;
};
export function useMergeQuery({ caller }: UseMergeQueryArgs = {}) {
const { queryEditor } = useEditorContext({
nonNull: true,
caller: caller || useMergeQuery,
});
const { schema } = useSchemaContext({ nonNull: true, caller: useMergeQuery });
return useCallback(() => {
const documentAST = queryEditor?.documentAST;
const query = queryEditor?.getValue();
if (!documentAST || !query) {
return;
}
queryEditor.setValue(print(mergeAst(documentAST, schema)));
}, [queryEditor, schema]);
}
type UsePrettifyEditorsArgs = {
/**
* This is only meant to be used internally in `@graphiql/react`.
*/
caller?: Function;
};
export function usePrettifyEditors({ caller }: UsePrettifyEditorsArgs = {}) {
const { queryEditor, headerEditor, variableEditor } = useEditorContext({
nonNull: true,
caller: caller || usePrettifyEditors,
});
return useCallback(() => {
if (variableEditor) {
const variableEditorContent = variableEditor.getValue();
try {
const prettifiedVariableEditorContent = JSON.stringify(
JSON.parse(variableEditorContent),
null,
2,
);
if (prettifiedVariableEditorContent !== variableEditorContent) {
variableEditor.setValue(prettifiedVariableEditorContent);
}
} catch {
/* Parsing JSON failed, skip prettification */
}
}
if (headerEditor) {
const headerEditorContent = headerEditor.getValue();
try {
const prettifiedHeaderEditorContent = JSON.stringify(
JSON.parse(headerEditorContent),
null,
2,
);
if (prettifiedHeaderEditorContent !== headerEditorContent) {
headerEditor.setValue(prettifiedHeaderEditorContent);
}
} catch {
/* Parsing JSON failed, skip prettification */
}
}
if (queryEditor) {
const editorContent = queryEditor.getValue();
const prettifiedEditorContent = print(parse(editorContent));
if (prettifiedEditorContent !== editorContent) {
queryEditor.setValue(prettifiedEditorContent);
}
}
}, [queryEditor, variableEditor, headerEditor]);
}
export type UseAutoCompleteLeafsArgs = {
/**
* A function to determine which field leafs are automatically added when
* trying to execute a query with missing selection sets. It will be called
* with the `GraphQLType` for which fields need to be added.
*/
getDefaultFieldNames?: GetDefaultFieldNamesFn;
/**
* This is only meant to be used internally in `@graphiql/react`.
*/
caller?: Function;
};
export function useAutoCompleteLeafs({
getDefaultFieldNames,
caller,
}: UseAutoCompleteLeafsArgs = {}) {
const { schema } = useSchemaContext({
nonNull: true,
caller: caller || useAutoCompleteLeafs,
});
const { queryEditor } = useEditorContext({
nonNull: true,
caller: caller || useAutoCompleteLeafs,
});
return useCallback(() => {
if (!queryEditor) {
return;
}
const query = queryEditor.getValue();
const { insertions, result } = fillLeafs(
schema,
query,
getDefaultFieldNames,
);
if (insertions && insertions.length > 0) {
queryEditor.operation(() => {
const cursor = queryEditor.getCursor();
const cursorIndex = queryEditor.indexFromPos(cursor);
queryEditor.setValue(result || '');
let added = 0;
const markers = insertions.map(({ index, string }) =>
queryEditor.markText(
queryEditor.posFromIndex(index + added),
queryEditor.posFromIndex(index + (added += string.length)),
{
className: 'auto-inserted-leaf',
clearOnEnter: true,
title: 'Automatically added leaf fields',
},
),
);
setTimeout(() => {
for (const marker of markers) {
marker.clear();
}
}, 7000);
let newCursorIndex = cursorIndex;
for (const { index, string } of insertions) {
if (index < cursorIndex) {
newCursorIndex += string.length;
}
}
queryEditor.setCursor(queryEditor.posFromIndex(newCursorIndex));
});
}
return result;
}, [getDefaultFieldNames, queryEditor, schema]);
}
export type InitialState = string | (() => string);
// https://react.dev/learn/you-might-not-need-an-effect
export const useEditorState = (editor: 'query' | 'variable' | 'header') => {
const context = useEditorContext({
nonNull: true,
});
const editorInstance = context[`${editor}Editor` as const];
let valueString = '';
const editorValue = editorInstance?.getValue() ?? false;
if (editorValue && editorValue.length > 0) {
valueString = editorValue;
}
const handleEditorValue = useCallback(
(value: string) => editorInstance?.setValue(value),
[editorInstance],
);
return useMemo<[string, (val: string) => void]>(
() => [valueString, handleEditorValue],
[valueString, handleEditorValue],
);
};
/**
* useState-like hook for current tab operations editor state
*/
export const useOperationsEditorState = (): [
operations: string,
setOperations: (content: string) => void,
] => {
return useEditorState('query');
};
/**
* useState-like hook for current tab variables editor state
*/
export const useVariablesEditorState = (): [
variables: string,
setVariables: (content: string) => void,
] => {
return useEditorState('variable');
};
/**
* useState-like hook for current tab variables editor state
*/
export const useHeadersEditorState = (): [
headers: string,
setHeaders: (content: string) => void,
] => {
return useEditorState('header');
};
/**
* Implements an optimistic caching strategy around a useState-like hook in
* order to prevent loss of updates when the hook has an internal delay and the
* update function is called again before the updated state is sent out.
*
* Use this as a wrapper around `useOperationsEditorState`,
* `useVariablesEditorState`, or `useHeadersEditorState` if you anticipate
* calling them with great frequency (due to, for instance, mouse, keyboard, or
* network events).
*
* Example:
*
* ```ts
* const [operationsString, handleEditOperations] =
* useOptimisticState(useOperationsEditorState());
* ```
*/
export function useOptimisticState([
upstreamState,
upstreamSetState,
]: ReturnType<typeof useEditorState>): ReturnType<typeof useEditorState> {
const lastStateRef = useRef({
/** The last thing that we sent upstream; we're expecting this back */
pending: null as string | null,
/** The last thing we received from upstream */
last: upstreamState,
});
const [state, setOperationsText] = useState(upstreamState);
useEffect(() => {
if (lastStateRef.current.last === upstreamState) {
// No change; ignore
} else {
lastStateRef.current.last = upstreamState;
if (lastStateRef.current.pending === null) {
// Gracefully accept update from upstream
setOperationsText(upstreamState);
} else if (lastStateRef.current.pending === upstreamState) {
// They received our update and sent it back to us - clear pending, and
// send next if appropriate
lastStateRef.current.pending = null;
if (upstreamState !== state) {
// Change has occurred; upstream it
lastStateRef.current.pending = state;
upstreamSetState(state);
}
} else {
// They got a different update; overwrite our local state (!!)
lastStateRef.current.pending = null;
setOperationsText(upstreamState);
}
}
}, [upstreamState, state, upstreamSetState]);
const setState = useCallback(
(newState: string) => {
setOperationsText(newState);
if (
lastStateRef.current.pending === null &&
lastStateRef.current.last !== newState
) {
// No pending updates and change has occurred... send it upstream
lastStateRef.current.pending = newState;
upstreamSetState(newState);
}
},
[upstreamSetState],
);
return useMemo(() => [state, setState], [state, setState]);
}