Skip to content
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

feat: add an opt-in feature to run multiple queries #1673

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion packages/graphiql/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,9 @@ GraphiQL supports customization in UI and behavior by accepting React props and

- `headerEditorEnabled`: an optional boolean which enables the header editor when `true`. Defaults to `false`.

- `shouldPersistHeaders`: an optional boolean which enables to persist headers to storage when `true`. Defaults to `false`
- `shouldPersistHeaders`: an optional boolean which enables to persist headers to storage when `true`. Defaults to `false`.

- `runMultipleQueries`: an optional boolean which enables to run multiple queries when `true`. The actual response of each query is returned as `data` object within the `yourQueryNameData` object. Defaults to `false`.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we link this to the spec document? is this what the spec document calls this feature?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The feature name is as suggested in the issue. Also I could not find the spec document for graphiql, it would be great if you could share the link!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i mean the spec document for this language feature. in the language spec. can you link to it in the readme here?


### Children (dropped as of 1.0.0-rc.2)

Expand Down
1 change: 1 addition & 0 deletions packages/graphiql/resources/renderExample.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ ReactDOM.render(
defaultVariableEditorOpen: true,
onEditOperationName: onEditOperationName,
headerEditorEnabled: true,
runMultipleQueries: true,
}),
document.getElementById('graphiql'),
);
165 changes: 165 additions & 0 deletions packages/graphiql/src/components/BatchExecuteButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
/**
* Copyright (c) 2020 GraphQL Contributors.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { MouseEventHandler } from 'react';
import { OperationDefinitionNode } from 'graphql';

/**
* BatchBatchExecuteButton
*
* What a nice round shiny button. Shows a drop-down checkbox when there are multiple
* queries to run.
*/

type BatchExecuteButtonProps = {
operations?: OperationDefinitionNode[];
isRunning: boolean;
onStop: () => void;
onRun: (value?: Array<string>) => void;
};

type BatchExecuteButtonState = {
optionsOpen: boolean;
highlight: OperationDefinitionNode | null;
};

export class BatchExecuteButton extends React.Component<
BatchExecuteButtonProps,
BatchExecuteButtonState
> {
constructor(props: BatchExecuteButtonProps) {
super(props);

this.state = {
optionsOpen: false,
highlight: null,
};
}

render() {
const operations = this.props.operations || [];
const optionsOpen = this.state.optionsOpen;
const hasOptions = operations && operations.length > 1;

let options = null;
if (hasOptions && optionsOpen) {
const highlight = this.state.highlight;
options = (
<ul className="execute-options">
<li
key="executeAll"
onMouseOver={event => event.currentTarget.classList.add('selected')}
onMouseOut={event =>
event.currentTarget.classList.remove('selected')
}
onMouseUp={() => this._onOptionSelected('executeAll')}>
{'Execute All'}
</li>
{operations.map((operation, i) => {
const opName = operation.name
? operation.name.value
: `<Unnamed ${operation.operation}>`;
return (
<li
key={`${opName}-${i}`}
className={operation === highlight ? 'selected' : undefined}
onMouseOver={() => this.setState({ highlight: operation })}
onMouseOut={() => this.setState({ highlight: null })}
onMouseUp={() => this._onOptionSelected(operation)}>
{opName}
</li>
);
})}
</ul>
);
}

// Allow click event if there is a running query or if there are not options
// for which operation to run.
let onClick;
if (this.props.isRunning || !hasOptions) {
onClick = this._onClick;
}

// Allow mouse down if there is no running query, there are options for
// which operation to run, and the dropdown is currently closed.
let onMouseDown: MouseEventHandler<HTMLButtonElement> = () => {};
if (!this.props.isRunning && hasOptions && !optionsOpen) {
onMouseDown = this._onOptionsOpen;
}

const pathJSX = this.props.isRunning ? (
<path d="M 10 10 L 23 10 L 23 23 L 10 23 z" />
) : (
<path d="M 11 9 L 24 16 L 11 23 z" />
);

return (
<div className="execute-button-wrap">
<button
type="button"
className="execute-button"
onMouseDown={onMouseDown}
onClick={onClick}
title="Execute Query (Ctrl-Enter)">
<svg width="34" height="34">
{pathJSX}
</svg>
</button>
{options}
</div>
);
}

_onClick = () => {
if (this.props.isRunning) {
this.props.onStop();
} else {
this.props.onRun();
}
};

_onOptionSelected = (operation: OperationDefinitionNode | string) => {
this.setState({ optionsOpen: false });
const selectedOperations: string[] = [];
if (typeof operation === 'string') {
this.props.operations?.map(operation => {
selectedOperations.push((operation.name && operation.name.value)!);
});
} else {
selectedOperations.push((operation.name && operation.name.value)!);
}
this.props.onRun(selectedOperations);
};

_onOptionsOpen: MouseEventHandler<HTMLButtonElement> = downEvent => {
let initialPress = true;
const downTarget = downEvent.currentTarget;
this.setState({ highlight: null, optionsOpen: true });

type MouseUpEventHandler = (upEvent: MouseEvent) => void;
let onMouseUp: MouseUpEventHandler | null = upEvent => {
if (initialPress && upEvent.target === downTarget) {
initialPress = false;
} else {
document.removeEventListener('mouseup', onMouseUp!);
onMouseUp = null;
const isOptionsMenuClicked =
upEvent.currentTarget &&
downTarget.parentNode?.compareDocumentPosition(
upEvent.currentTarget as Node,
) &&
Node.DOCUMENT_POSITION_CONTAINED_BY;
if (!isOptionsMenuClicked) {
// menu calls setState if it was clicked
this.setState({ optionsOpen: false });
}
}
};

document.addEventListener('mouseup', onMouseUp);
};
}
52 changes: 43 additions & 9 deletions packages/graphiql/src/components/GraphiQL.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
} from 'graphql';
import copyToClipboard from 'copy-to-clipboard';

import { BatchExecuteButton } from './BatchExecuteButton';
import { ExecuteButton } from './ExecuteButton';
import { ImagePreview } from './ImagePreview';
import { ToolbarButton } from './ToolbarButton';
Expand Down Expand Up @@ -123,6 +124,7 @@ export type GraphiQLProps = {
ResultsTooltip?: typeof Component | FunctionComponent;
readOnly?: boolean;
docExplorerOpen?: boolean;
runMultipleQueries?: boolean;
};

export type GraphiQLState = {
Expand Down Expand Up @@ -502,12 +504,22 @@ export class GraphiQL extends React.Component<GraphiQLProps, GraphiQLState> {
<div className="topBarWrap">
<div className="topBar">
{logo}
<ExecuteButton
isRunning={Boolean(this.state.subscription)}
onRun={this.handleRunQuery}
onStop={this.handleStopQuery}
operations={this.state.operations}
/>
{!this.props.runMultipleQueries && (
<ExecuteButton
isRunning={Boolean(this.state.subscription)}
onRun={this.handleRunQuery}
onStop={this.handleStopQuery}
operations={this.state.operations}
/>
)}
{this.props.runMultipleQueries && (
<BatchExecuteButton
isRunning={Boolean(this.state.subscription)}
onRun={this.handleRunMultipleQueries}
onStop={this.handleStopQuery}
operations={this.state.operations}
/>
)}
{toolbar}
</div>
{!this.state.docExplorerOpen && (
Expand Down Expand Up @@ -1009,24 +1021,46 @@ export class GraphiQL extends React.Component<GraphiQLProps, GraphiQLState> {
operationName as string,
shouldPersistHeaders as boolean,
(result: FetcherResult) => {
if (queryID === this._editorQueryID) {
if (
queryID === this._editorQueryID ||
this.props.runMultipleQueries
) {
const responsesSoFar = JSON.parse(
this.state.response != undefined ? this.state.response : '{}',
);
responsesSoFar[selectedOperationName + 'Data'] = result;

this.setState({
isWaitingForResponse: false,
response: GraphiQL.formatResult(result),
response: this.props.runMultipleQueries
? GraphiQL.formatResult(responsesSoFar)
: GraphiQL.formatResult(result),
});
}
},
);

this.setState({ subscription });
} catch (error) {
const responsesSoFar = JSON.parse(
this.state.response != undefined ? this.state.response : '{}',
);
responsesSoFar[selectedOperationName + 'Response'] = error.message;
this.setState({
isWaitingForResponse: false,
response: error.message,
response: this.props.runMultipleQueries
? GraphiQL.formatResult(responsesSoFar)
: GraphiQL.formatResult(error.message),
});
}
};

handleRunMultipleQueries = (selectedOperationNames?: Array<string>) => {
selectedOperationNames?.map(selectedOperationName => {
this.handleRunQuery(selectedOperationName);
});
};

handleStopQuery = () => {
const subscription = this.state.subscription;
this.setState({
Expand Down