-
Notifications
You must be signed in to change notification settings - Fork 1.8k
WIP: incremental payloads UI #3601
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
thomasheyenbrock
wants to merge
4
commits into
main
Choose a base branch
from
incremental-payloads-ui
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+466
−82
Draft
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
--- | ||
'graphiql': minor | ||
'@graphiql/react': minor | ||
--- | ||
|
||
Add a UI to the response pane that shows incremental payloads for streamed responses (subscriptions, defer, stream) |
141 changes: 141 additions & 0 deletions
141
packages/graphiql-react/src/editor/components/increments-editors.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,141 @@ | ||
import { useCallback, useEffect, useRef, useState } from 'react'; | ||
|
||
import { ChevronDownIcon, ChevronUpIcon } from '../../icons'; | ||
import { UnStyledButton } from '../../ui'; | ||
import { | ||
commonKeys, | ||
DEFAULT_EDITOR_THEME, | ||
DEFAULT_KEY_MAP, | ||
importCodeMirror, | ||
} from '../common'; | ||
import { useSynchronizeOption } from '../hooks'; | ||
import { IncrementalPayload } from '../tabs'; | ||
import { CodeMirrorEditor, CommonEditorProps } from '../types'; | ||
|
||
import '../style/codemirror.css'; | ||
import '../style/fold.css'; | ||
import '../style/lint.css'; | ||
import '../style/hint.css'; | ||
import '../style/info.css'; | ||
import '../style/jump.css'; | ||
import '../style/auto-insertion.css'; | ||
import '../style/editor.css'; | ||
import '../style/increments-editors.css'; | ||
|
||
type UseIncrementsEditorArgs = CommonEditorProps & { | ||
increment: IncrementalPayload; | ||
}; | ||
|
||
function useIncrementsEditor({ | ||
editorTheme = DEFAULT_EDITOR_THEME, | ||
keyMap = DEFAULT_KEY_MAP, | ||
increment, | ||
}: UseIncrementsEditorArgs) { | ||
const [editor, setEditor] = useState<CodeMirrorEditor | null>(null); | ||
|
||
const ref = useRef<HTMLDivElement>(null); | ||
|
||
useEffect(() => { | ||
let isActive = true; | ||
void importCodeMirror( | ||
[ | ||
import('codemirror/addon/fold/foldgutter'), | ||
import('codemirror/addon/fold/brace-fold'), | ||
import('codemirror/addon/dialog/dialog'), | ||
import('codemirror/addon/search/search'), | ||
import('codemirror/addon/search/searchcursor'), | ||
import('codemirror/addon/search/jump-to-line'), | ||
// @ts-expect-error | ||
import('codemirror/keymap/sublime'), | ||
import('codemirror-graphql/esm/results/mode'), | ||
import('codemirror-graphql/esm/utils/info-addon'), | ||
], | ||
{ useCommonAddons: false }, | ||
).then(CodeMirror => { | ||
// Don't continue if the effect has already been cleaned up | ||
if (!isActive) { | ||
return; | ||
} | ||
|
||
const container = ref.current; | ||
if (!container) { | ||
return; | ||
} | ||
|
||
const newEditor = CodeMirror(container, { | ||
value: JSON.stringify(increment.payload, null, 2), | ||
lineWrapping: true, | ||
readOnly: true, | ||
theme: editorTheme, | ||
mode: 'graphql-results', | ||
foldGutter: true, | ||
gutters: ['CodeMirror-foldgutter'], | ||
// @ts-expect-error | ||
info: true, | ||
extraKeys: commonKeys, | ||
}); | ||
|
||
setEditor(newEditor); | ||
}); | ||
|
||
return () => { | ||
isActive = false; | ||
}; | ||
}, [editorTheme, increment.payload]); | ||
|
||
useSynchronizeOption(editor, 'keyMap', keyMap); | ||
|
||
return ref; | ||
} | ||
|
||
function IncrementEditor( | ||
props: UseIncrementsEditorArgs & { isInitial: boolean }, | ||
) { | ||
const [isOpen, setIsOpen] = useState(false); | ||
const incrementEditor = useIncrementsEditor(props); | ||
|
||
const toggleEditor = useCallback(() => setIsOpen(current => !current), []); | ||
|
||
return ( | ||
<div | ||
className="graphiql-increment-editor" | ||
style={isOpen ? { height: '30vh' } : {}} | ||
> | ||
<UnStyledButton | ||
className="graphiql-increment-editor-toggle" | ||
onClick={toggleEditor} | ||
> | ||
{props.isInitial ? 'Initial payload' : 'Increment'} (after{' '} | ||
{props.increment.timing / 1000}s) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. TODO: Show in ms if the timing is <1s, otherwise show seconds |
||
{isOpen ? ( | ||
<ChevronUpIcon className="graphiql-increment-editor-chevron" /> | ||
) : ( | ||
<ChevronDownIcon className="graphiql-increment-editor-chevron" /> | ||
)} | ||
</UnStyledButton> | ||
<div | ||
ref={incrementEditor} | ||
className={`graphiql-editor ${isOpen ? '' : 'hidden'}`} | ||
/> | ||
</div> | ||
); | ||
} | ||
|
||
export type IncrementsEditorsProps = CommonEditorProps & { | ||
incrementalPayloads: IncrementalPayload[]; | ||
}; | ||
|
||
export function IncrementsEditors(props: IncrementsEditorsProps) { | ||
return ( | ||
<div className="graphiql-increments-editors"> | ||
{props.incrementalPayloads.map((increment, index) => ( | ||
<IncrementEditor | ||
key={increment.timing} | ||
isInitial={index === 0} | ||
increment={increment} | ||
{...props} | ||
/> | ||
))} | ||
</div> | ||
); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,8 @@ | ||
export { HeaderEditor } from './header-editor'; | ||
export { ImagePreview } from './image-preview'; | ||
export { IncrementsEditors } from './increments-editors'; | ||
export { QueryEditor } from './query-editor'; | ||
export { ResponseEditor } from './response-editor'; | ||
export { VariableEditor } from './variable-editor'; | ||
|
||
export type { IncrementsEditorsProps } from './increments-editors'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
31 changes: 31 additions & 0 deletions
31
packages/graphiql-react/src/editor/style/increments-editors.css
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
.graphiql-increments-editors { | ||
display: flex; | ||
flex-direction: column; | ||
padding: var(--px-16); | ||
} | ||
|
||
.graphiql-increment-editor { | ||
padding: var(--px-4) 0; | ||
display: flex; | ||
flex-direction: column; | ||
position: relative; | ||
} | ||
|
||
.graphiql-increment-editor + .graphiql-increment-editor { | ||
border-top: 1px solid | ||
hsla(var(--color-neutral), var(--alpha-background-heavy)); | ||
} | ||
|
||
.graphiql-increment-editor-toggle, | ||
button.graphiql-increment-editor-toggle { | ||
padding: var(--px-2) var(--px-4); | ||
display: flex; | ||
justify-content: space-between; | ||
align-items: center; | ||
} | ||
|
||
.graphiql-increment-editor-chevron { | ||
height: var(--px-12); | ||
width: var(--px-12); | ||
margin-left: var(--px-4); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -9,17 +9,22 @@ import { | |||||
import { | ||||||
ExecutionResult, | ||||||
FragmentDefinitionNode, | ||||||
GraphQLError, | ||||||
getOperationAST, | ||||||
OperationTypeNode, | ||||||
print, | ||||||
} from 'graphql'; | ||||||
import { getFragmentDependenciesForAST } from 'graphql-language-service'; | ||||||
import { ReactNode, useCallback, useMemo, useRef, useState } from 'react'; | ||||||
import setValue from 'set-value'; | ||||||
|
||||||
import { useAutoCompleteLeafs, useEditorContext } from './editor'; | ||||||
import { UseAutoCompleteLeafsArgs } from './editor/hooks'; | ||||||
import { IncrementalPayload } from './editor/tabs'; | ||||||
import { useHistoryContext } from './history'; | ||||||
import { createContextHook, createNullableContext } from './utility/context'; | ||||||
import { | ||||||
IncrementalResult, | ||||||
mergeIncrementalResult, | ||||||
} from './utility/incremental'; | ||||||
|
||||||
export type ExecutionContextType = { | ||||||
/** | ||||||
|
@@ -30,8 +35,9 @@ export type ExecutionContextType = { | |||||
isFetching: boolean; | ||||||
/** | ||||||
* If there is currently a GraphQL request in-flight. For multi-part | ||||||
* requests like subscriptions, this will be `true` until the last batch | ||||||
* has been fetched or the connection is closed from the client. | ||||||
* requests (subscriptions, defer, stream, etc.), this will be `true` until | ||||||
* the last batch has been fetched or the connection is closed from the | ||||||
* client. | ||||||
*/ | ||||||
isSubscribed: boolean; | ||||||
/** | ||||||
|
@@ -119,9 +125,25 @@ export function ExecutionContextProvider({ | |||||
return; | ||||||
} | ||||||
|
||||||
const setResponse = (value: string) => { | ||||||
// Clear any incremental results of previous runs | ||||||
updateActiveTabValues({ incrementalPayloads: [] }); | ||||||
|
||||||
const startTime = Date.now(); | ||||||
const incrementalPayloads: IncrementalPayload[] = []; | ||||||
const setResponse = ( | ||||||
value: string, | ||||||
incrementalPayload?: ExecutionResult | IncrementalResult[], | ||||||
) => { | ||||||
responseEditor.setValue(value); | ||||||
updateActiveTabValues({ response: value }); | ||||||
|
||||||
if (incrementalPayload) { | ||||||
incrementalPayloads.push({ | ||||||
timing: Date.now() - startTime, | ||||||
payload: incrementalPayload, | ||||||
}); | ||||||
} | ||||||
|
||||||
updateActiveTabValues({ response: value, incrementalPayloads }); | ||||||
}; | ||||||
|
||||||
queryIdRef.current += 1; | ||||||
|
@@ -179,6 +201,12 @@ export function ExecutionContextProvider({ | |||||
|
||||||
const opName = operationName ?? queryEditor.operationName ?? undefined; | ||||||
|
||||||
let isSubscription = false; | ||||||
if (queryEditor.documentAST) { | ||||||
const operation = getOperationAST(queryEditor.documentAST, opName); | ||||||
isSubscription = operation?.operation === OperationTypeNode.SUBSCRIPTION; | ||||||
} | ||||||
|
||||||
history?.addToHistory({ | ||||||
query, | ||||||
variables: variablesString, | ||||||
|
@@ -188,9 +216,9 @@ export function ExecutionContextProvider({ | |||||
|
||||||
try { | ||||||
const fullResponse: ExecutionResult = {}; | ||||||
const handleResponse = (result: ExecutionResult) => { | ||||||
// A different query was dispatched in the meantime, so don't | ||||||
// show the results of this one. | ||||||
const handleResponse = (result: ExecutionResult, isStreaming = false) => { | ||||||
// A different query was dispatched in the meantime, so discard the | ||||||
// results of this one. | ||||||
if (queryId !== queryIdRef.current) { | ||||||
return; | ||||||
} | ||||||
|
@@ -211,11 +239,11 @@ export function ExecutionContextProvider({ | |||||
} | ||||||
|
||||||
setIsFetching(false); | ||||||
setResponse(formatResult(fullResponse)); | ||||||
setResponse(formatResult(fullResponse), maybeMultipart); | ||||||
} else { | ||||||
const response = formatResult(result); | ||||||
setIsFetching(false); | ||||||
setResponse(response); | ||||||
setResponse(response, isStreaming ? result : undefined); | ||||||
} | ||||||
}; | ||||||
|
||||||
|
@@ -231,15 +259,35 @@ export function ExecutionContextProvider({ | |||||
}, | ||||||
); | ||||||
|
||||||
// Subscriptions are always considered streamed responses | ||||||
let isStreaming = isSubscription; | ||||||
|
||||||
const value = await Promise.resolve(fetch); | ||||||
if (isObservable(value)) { | ||||||
// 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. | ||||||
// | ||||||
// Note: The naming of the React state assumes that in this case the | ||||||
// operation is a subscription (which in practice it most likely is), | ||||||
// but technically it can also be a query or mutation where the fetcher | ||||||
// decided to return an observable with either a single payload or | ||||||
// multiple payloads (defer/stream). As the naming is part of the | ||||||
// public API of this context we decide not to change it until defer/ | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
// stream is officially part of the GraphQL spec. | ||||||
setSubscription( | ||||||
value.subscribe({ | ||||||
next(result) { | ||||||
handleResponse(result); | ||||||
handleResponse( | ||||||
result, | ||||||
// If the initial payload contains `hasNext` for a query or | ||||||
// mutation then we know it's a streamed response. | ||||||
isStreaming || result.hasNext, | ||||||
); | ||||||
|
||||||
// If there's more than one payload then we're streaming, so set | ||||||
// this flag to `true` for any future calls to `next`. | ||||||
isStreaming = true; | ||||||
}, | ||||||
error(error: Error) { | ||||||
setIsFetching(false); | ||||||
|
@@ -258,9 +306,20 @@ export function ExecutionContextProvider({ | |||||
setSubscription({ | ||||||
unsubscribe: () => value[Symbol.asyncIterator]().return?.(), | ||||||
}); | ||||||
|
||||||
for await (const result of value) { | ||||||
handleResponse(result); | ||||||
handleResponse( | ||||||
result, | ||||||
// If the initial payload contains `hasNext` for a query or | ||||||
// mutation then we know it's a streamed response. | ||||||
isStreaming || result.hasNext, | ||||||
); | ||||||
|
||||||
// If there's more than one payload then we're streaming, so set this | ||||||
// flag to `true` for any future loop iterations. | ||||||
isStreaming = true; | ||||||
} | ||||||
|
||||||
setIsFetching(false); | ||||||
setSubscription(null); | ||||||
} else { | ||||||
|
@@ -333,61 +392,3 @@ function tryParseJsonObject({ | |||||
} | ||||||
return parsed; | ||||||
} | ||||||
|
||||||
type IncrementalResult = { | ||||||
data?: Record<string, unknown> | null; | ||||||
errors?: ReadonlyArray<GraphQLError>; | ||||||
extensions?: Record<string, unknown>; | ||||||
hasNext?: boolean; | ||||||
path?: ReadonlyArray<string | number>; | ||||||
incremental?: ReadonlyArray<IncrementalResult>; | ||||||
label?: string; | ||||||
items?: ReadonlyArray<Record<string, unknown>> | null; | ||||||
}; | ||||||
|
||||||
/** | ||||||
* @param executionResult The complete execution result object which will be | ||||||
* mutated by merging the contents of the incremental result. | ||||||
* @param incrementalResult The incremental result that will be merged into the | ||||||
* complete execution result. | ||||||
*/ | ||||||
function mergeIncrementalResult( | ||||||
executionResult: ExecutionResult, | ||||||
incrementalResult: IncrementalResult, | ||||||
): void { | ||||||
const path = ['data', ...(incrementalResult.path ?? [])]; | ||||||
|
||||||
if (incrementalResult.items) { | ||||||
for (const item of incrementalResult.items) { | ||||||
setValue(executionResult, path.join('.'), item); | ||||||
// Increment the last path segment (the array index) to merge the next item at the next index | ||||||
// eslint-disable-next-line unicorn/prefer-at -- cannot mutate the array using Array.at() | ||||||
(path[path.length - 1] as number)++; | ||||||
} | ||||||
} | ||||||
|
||||||
if (incrementalResult.data) { | ||||||
setValue(executionResult, path.join('.'), incrementalResult.data, { | ||||||
merge: true, | ||||||
}); | ||||||
} | ||||||
|
||||||
if (incrementalResult.errors) { | ||||||
executionResult.errors ||= []; | ||||||
(executionResult.errors as GraphQLError[]).push( | ||||||
...incrementalResult.errors, | ||||||
); | ||||||
} | ||||||
|
||||||
if (incrementalResult.extensions) { | ||||||
setValue(executionResult, 'extensions', incrementalResult.extensions, { | ||||||
merge: true, | ||||||
}); | ||||||
} | ||||||
|
||||||
if (incrementalResult.incremental) { | ||||||
for (const incrementalSubResult of incrementalResult.incremental) { | ||||||
mergeIncrementalResult(executionResult, incrementalSubResult); | ||||||
} | ||||||
} | ||||||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
import { ExecutionResult, GraphQLError } from 'graphql'; | ||
import setValue from 'set-value'; | ||
|
||
/** | ||
* @param executionResult The complete execution result object which will be | ||
* mutated by merging the contents of the incremental result. | ||
* @param incrementalResult The incremental result that will be merged into the | ||
* complete execution result. | ||
*/ | ||
export function mergeIncrementalResult( | ||
executionResult: ExecutionResult, | ||
incrementalResult: IncrementalResult, | ||
): void { | ||
const path = ['data', ...(incrementalResult.path ?? [])]; | ||
|
||
if (incrementalResult.items) { | ||
for (const item of incrementalResult.items) { | ||
setValue(executionResult, path.join('.'), item); | ||
// Increment the last path segment (the array index) to merge the next item at the next index | ||
// eslint-disable-next-line unicorn/prefer-at -- cannot mutate the array using Array.at() | ||
(path[path.length - 1] as number)++; | ||
} | ||
} | ||
|
||
if (incrementalResult.data) { | ||
setValue(executionResult, path.join('.'), incrementalResult.data, { | ||
merge: true, | ||
}); | ||
} | ||
|
||
if (incrementalResult.errors) { | ||
executionResult.errors ||= []; | ||
(executionResult.errors as GraphQLError[]).push( | ||
...incrementalResult.errors, | ||
); | ||
} | ||
|
||
if (incrementalResult.extensions) { | ||
setValue(executionResult, 'extensions', incrementalResult.extensions, { | ||
merge: true, | ||
}); | ||
} | ||
|
||
if (incrementalResult.incremental) { | ||
for (const incrementalSubResult of incrementalResult.incremental) { | ||
mergeIncrementalResult(executionResult, incrementalSubResult); | ||
} | ||
} | ||
} | ||
|
||
export type IncrementalResult = { | ||
data?: Record<string, unknown> | null; | ||
errors?: ReadonlyArray<GraphQLError>; | ||
extensions?: Record<string, unknown>; | ||
hasNext?: boolean; | ||
path?: ReadonlyArray<string | number>; | ||
incremental?: ReadonlyArray<IncrementalResult>; | ||
label?: string; | ||
items?: ReadonlyArray<Record<string, unknown>> | null; | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For the editors to show properly I needed to give the wrapper a fixed height, which is not ideal. But I don't see a better way right now other than starting to do JS magic to calculate the container height on-runtime.